从对象中删除n个元素

时间:2018-03-14 10:42:42

标签: reactjs ecmascript-6

我有像

这样的对象
obj = {name:"xxx" , des1:"x",des2:"xx",des3:"xxx" , age:"12"}. 

但根据用户输入,des的属性可以增加为des1,des2,des3,des4 ...。所以基本上我们不知道对象中有多少“des”属性。

我想做这样的事情。在数组中获取desput它们的所有属性。然后按如下所示更新对象

obj = {name:"xxx" , description:["x","xx","xxx"] , age:"12"}

如何使用ES6 syntax

实现此目的

3 个答案:

答案 0 :(得分:1)

您可以通过以下方式转换数据:

const transformed = Object.keys(obj).reduce(
(acc, key) => {
  return key === 'name' || key === 'age'
    ? { ...acc, [key]: obj[key] }
    : { ...acc, description: [...acc.description, obj[key]] }
},
{ description: [] }
)

答案 1 :(得分:1)

这个怎么样?

const f = {name:"xxx", des1:"x", des2:"xx", des3:"xxx", age:"12"};

const { name, age, ...rest} = f;
const result = { name, age, description: Object.values(rest) };

console.log(result) // { name: 'xxx', age: '12', description: [ 'x', 'xx', 'xxx' ] }

答案 2 :(得分:0)

您可以使用reduce,然后将string与正则表达式匹配,该正则表达式检查字符串是否为des,后跟数字



var obj = {name:"xxx" , des1:"x",des2:"xx",des3:"xxx" , age:"12"}
const res = Object.keys(obj).reduce((acc, key)=> {
   if(key.match(/^des([0-9]+)$/)) {
      if(acc.description) {
         acc.description.push(obj[key]);
      } else {
         acc.description = [obj[key]];
      } 
   } else {
      acc[key] = obj[key];
   }
   return acc;
}, {})

console.log(res);




相关问题