如何合并3个具有修改后值的JavaScript对象

时间:2018-12-10 10:29:16

标签: javascript html arrays json

我有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 个答案:

答案 0 :(得分:2)

您可以使用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))

答案 1 :(得分:2)

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 :(得分:-2)

使用对象分配:

Object.assign(ob1,ob2);