首页 > 解决方案 > 在javascript中的对象数组中合并具有相同键的对象

问题描述

我有一个对象数组,如下所示。如果数组中有具有相同键值的对象,那么生成的数组应该包含 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"
        }
    ]
}

]

谁能帮我解决这个问题?提前致谢

标签: javascriptarraysjavascript-objectsecmascript-5

解决方案


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;
}, []);

推荐阅读