如何将3个javascript对象与修改后的值合并

我有3个对象,如[

const arr = [
{name:'ABC', value:123},
{name:'ABC', value:456},
{name:'ABC',value:789},
{name:'DEF',value:9999},
name:'DEF', value:0000}
]

我想输出像

updatedArr = [
  {name:'ABC', value:123, value1:456, value2:789}
  {name:'DEF', value:9999, value1:0000}
]

关于此的任何类型的链接也将有所帮助 .

回答(3)

2 years ago

const arr = [{
    name: 'ABC',
    value: 123
  },
  {
    name: 'ABC',
    value: 456
  },
  {
    name: 'ABC',
    value: 789
  },
  {
    name: 'DEF',
    value: 9999
  },
  {
    name: 'DEF',
    value: 0000
  }
]

const res = Object.values(arr.reduce((acc, item) => {
  if (!acc[item.name]) {
    acc[item.name] = item;
  } else {
    acc[item.name]['value' + (Object.keys(acc[item.name]).length - 1)] = item.value;
  }

  return acc;
}, {}));

console.log(res)

2 years ago

您可以使用 reduce 方法创建对象,然后使用 Object.values 来获取值数组 .

const arr = [{name:'ABC', value:123},{name:'ABC', value:456},{name:'ABC',value:789},{name:'DEF',value:9999},{name:'DEF', value:0000}]

const res = arr.reduce((r, e) => {
  if(!r[e.name]) r[e.name] = {...e}
  else {
    let {name, ...rest} = r[e.name];
    r[e.name][`value${Object.keys(rest).length}`] = e.value
  }
  return r;
}, {});

console.log(Object.values(res))

2 years ago

使用对象分配:

Object.assign(ob1,ob2);