在javascript中的对象数组中合并具有相同键的对象

时间:2020-08-21 13:10:47

标签: javascript arrays javascript-objects ecmascript-5

我有一个对象数组,如下所示。如果该数组包含键值相同的对象,则生成的数组应包含ES5版本中这两个对象的组合

var arr = [
{
    "abc": [
        {
            "name": "test",
            "addr": "123",
       }
    ]
},
{
    "def": [
        {
            "first_name": "test",
            "last_name": "test"
        }
    ]
},
{
    "def": [
        {
            "first_name": "test1",
            "last_name": "test1"
        }
    ]
}

]

预期输出应为

var arr =[
{
    "abc": [
        {
            "name": "test",
            "addr": "123",
        }
    ]
},
{
    "def": [
        {
            "first_name": "test",
            "last_name": "test"
        },
        {
            "first_name": "test1",
            "last_name": "test1"
        }
    ]
}

]

有人可以帮助我实现这一目标吗?预先感谢

2 个答案:

答案 0 :(得分:1)

var arr = [
{
    "abc": [
        {
            "name": "test",
            "addr": "123",
       }
    ]
},
{
    "def": [
        {
            "first_name": "test",
            "last_name": "test"
        }
    ]
},
{
    "def": [
        {
            "first_name": "test1",
            "last_name": "test1"
        }
    ]
}]

const result = arr.reduce((acc, curr) => {        
    const key = Object.keys(curr)[0]
    const found = acc.find(i => i[key])
    if (!found) {
        acc.push(curr)
    } else {
        found[key] = [ ...found[key], ...curr[key] ]
    }
    return acc;
}, [])

console.log(result)

下面的代码应该可以得到预期的结果。

ES6

arr.reduce((acc, curr) => {        
    const key = Object.keys(curr)[0]
    const found = acc.find(i => i[key])
    if (!found) {
        acc.push(curr)
    } else {
        found[key] = [ ...found[key], ...curr[key] ]
    }
    return acc;
}, [])

ES5

arr.reduce(function (acc, curr) {
  var key = Object.keys(curr)[0];
  var found = acc.find(function (i) {
    return i[key];
  });

  if (!found) {
    acc.push(curr);
  } else {
    found[key] = [].concat(found[key], curr[key]);
  }

  return acc;
}, []);

使用filter代替find

arr.reduce(function (acc, curr) {
  var key = Object.keys(curr)[0];
  var found = acc.filter(function (i) {
    return i[key];
  })[0];

  if (!found) {
    acc.push(curr);
  } else {
    found[key] = [].concat(found[key], curr[key]);
  }

  return acc;
}, []);

答案 1 :(得分:0)

使用objectarray

var arr = [{
    "abc": [{
      "name": "test",
      "addr": "123",
    }]
  },
  {
    "def": [{
      "first_name": "test",
      "last_name": "test"
    }]
  },
  {
    "def": [{
      "first_name": "test1",
      "last_name": "test1"
    }]
  }
]

var b = {}

arr.forEach(c => {
  var key = Object.keys(c)[0]
  var value = Object.values(c)[0]
  if (!b[key]) b[key] = []
  b[key].push(...value)
})

// b is resultant object

var c = []
Object.keys(b).forEach(v => {
  let a = {};
  a[v] = b[v];
  c.push(a)
})

// c is converting object to array

console.log(c)