按值合并2个JS对象数组

时间:2019-04-13 15:27:26

标签: javascript arrays merge

问题

我有两个需要合并的对象的Javascript数组。我需要通过匹配每个数组中包含的单个key:value对的唯一值来合并。我要合并的值的键不同

我想添加键:基于匹配的唯一值,将数组2中的值对添加到数组1中的正确对象。 array1.user和array2._id的值是我需要匹配的值。

数组

const array1 = [ { _id: 5c6c7132f9bf4bdab9c906ff,
    user: 5c65d9438e4a834c8e85dd7d },
  { _id: 5c6ccd6d3a0dc4e4951c2bee,
    user: 5c65d9438e4a834c8e85dd7e } ]

const array2 = users [ { _id: 5c65d9438e4a834c8e85dd7d,
    info: { name: 'John', city: 'New York' } },
  { _id: 5c65d9438e4a834c8e85dd7e,
    info: { name: 'Paneer', city: 'San Fran' } } ]

我尝试过的

我已经尝试过使用lodash的_.map和_.extend函数,但我是lodash的新手,它没有给我合适的输出

  const mergedArray = _.map(array1, function(item){
    return _.extend(item, _.find(array2, {_id: item.user}));
  });

结果

mergedArray [ { _id: 5c65d9438e4a834c8e85dd7d,
    info: { name: 'John', city: 'New York' } },
  { _id: 5c65d9438e4a834c8e85dd7e,
    info: { name: 'Paneer', city: 'San Fran' } }]

所需结果

const mergedArray = [ { _id: 5c6c7132f9bf4bdab9c906ff,
    user: 5c65d9438e4a834c8e85dd7d,
    info: { name: 'John', city: 'New York' } } ,
  { _id: 5c6ccd6d3a0dc4e4951c2bee,
    user: 5c65d9438e4a834c8e85dd7e, 
    info: { name: 'Paneer', city: 'San Fran' } } ]

3 个答案:

答案 0 :(得分:1)

您可以使用mapfind

如果数组的映射顺序与避免使用find

的顺序相同

const array1 = [ { _id: `5c6c7132f9bf4bdab9c906ff`,user: `5c65d9438e4a834c8e85dd7d` },{ _id: `5c6ccd6d3a0dc4e4951c2bee`,user: `5c65d9438e4a834c8e85dd7e` }]
const array2 =[ { _id: `5c65d9438e4a834c8e85dd7d`,info: { name: 'John', city: 'New York' } },{ _id: `5c65d9438e4a834c8e85dd7e`,info: { name: 'Paneer', city: 'San Fran' } } ]
    
const final = array1.map(e=> {
  const found = array2.find(({_id}) => e.user === _id)
  return {
    ...e,
    info : found.info
  }
})

console.log(final)

答案 1 :(得分:1)

您可以使用Map并为结果构建新对象。

const
    array1 = [{ _id: '5c6c7132f9bf4bdab9c906ff', user: '5c65d9438e4a834c8e85dd7d' }, { _id: '5c6ccd6d3a0dc4e4951c2bee', user: '5c65d9438e4a834c8e85dd7e' }],
    array2 = [{ _id: '5c65d9438e4a834c8e85dd7d', info: { name: 'John', city: 'New York' } }, { _id: '5c65d9438e4a834c8e85dd7e', info: { name: 'Paneer', city: 'San Fran' } }],
    users = new Map(array2.map(({ _id, info }) => [_id, { info }])),
    merged = array1.map(o => ({ ...o, ...(users.get(o.user) || {}) }));

console.log(merged);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

另一种方法是使用键生成对象,然后使用该生成的对象直接获取值。密钥访问非常快。

const array1 = [ { _id: "5c6c7132f9bf4bdab9c906ff",user: "5c65d9438e4a834c8e85dd7d" },{ _id: "5c6ccd6d3a0dc4e4951c2bee",user: "5c65d9438e4a834c8e85dd7e" } ];
const ids = array1.reduce((a, {user, _id}) => ({...a, [user]: _id}), {});
const array2 = [ { _id: "5c65d9438e4a834c8e85dd7d",info: { name:'John', city: 'New York' } },{ _id: "5c65d9438e4a834c8e85dd7e", info: { name: 'Paneer', city: 'San Fran' } } ];
    
array2.forEach(o => {
  o.user = o._id;
  o._id = ids[o._id];
});

console.log(array2);
.as-console-wrapper { max-height: 100% !important; top: 0; }