简体   繁体   English

如何合并来自两个 arrays 的对象

[英]How to merge objects from two arrays

I have two arrays of objects我有两个 arrays 对象

    let current = [
        {
            categoryId: 18,
            id: 'fire_18',
            test: 'test'
        }, {
            oldItem: "items that dont exist in new array should be deleted"
        }
    ]

    let new_data = [
        {
            id: 'fire_18',
            categoryId: 18,
            test1: 'test1',
        }, {
            newItem: "new items should be added to final"
        }
    ]

I need to merge those so the result is not missing data from current array.我需要合并它们,这样结果就不会丢失current数组中的数据。 The desired result looks like this期望的结果看起来像这样

    [
        {
            id: 'fire_18',
            categoryId: 18,
            test1: 'test1',
            test: 'test'
        }, {
            newItem: "new items should be added to final"
        }
    ]

Here is my attempt这是我的尝试

 let current = [ { categoryId: 18, id: 'fire_18', test: 'test' }, { oldItem: "items that dont exist in new array should be deleted" } ] let new_data = [ { id: 'fire_18', categoryId: 18, test1: 'test1', }, { newItem: "new items should be added to final" } ] console.log(' === Current ==>', current); console.log(' === New ==>', new_data); new_data.map(newItem => { let currentMatch; try { // incase new item newItem.categoryId wont exist currentMatch = current.find(c => c.categoryId == newItem.categoryId) || {}; } catch (error) { // in that case, no need to merge currentMatch = {}; } return Object.assign(currentMatch, newItem); }); console.log(' === Merged ==>', new_data);

the main thing wrong still is test key from the current arr is missing after merge.主要的错误仍然是合并后缺少current arr 的test密钥。

Can anyone modify the pen to not delete keys from the current arr?任何人都可以修改笔以不从current arr 中删除键吗?

Note that Array.map method returns a new array.请注意, Array.map方法返回一个新数组。 You are not logging this merged new array - but one of your old arrays.您没有记录这个合并的新阵列 - 而是您的旧 arrays 之一。

Also, you don't need try catch here.此外,您不需要在这里try catch You may also note that if the categoryId is undefined, the objects will still match.您可能还注意到,如果categoryId未定义,对象仍将匹配。 So, you need a check for that.所以,你需要检查一下。

 let current = [ { categoryId: 18, id: 'fire_18', test: 'test' }, { oldItem: "items that dont exist in new array should be deleted" } ] let new_data = [ { id: 'fire_18', categoryId: 18, test1: 'test1', }, { newItem: "new items should be added to final" } ] newArray = new_data.map(newItem => { let currentMatch; currentMatch = current.find(c => c.categoryId === newItem.categoryId && newItem.categoryId) || {}; return Object.assign(currentMatch, newItem); }); console.log(' === Merged ==>', newArray);

You can use lodash for this.您可以为此使用 lodash。

finalArr = _(_.flatten([current, new_data]))
                                        .groupBy('id')
                                        .map(_.spread(_.assign))
                                        .value();

Like this?像这样? I'm not sure what you're expecting to happen with the newItem and oldItem entries.我不确定您期望newItemoldItem条目会发生什么。

 let current = [{ categoryId: 18, id: 'fire_18', test: 'test' }] let new_data = [{ id: 'fire_18', categoryId: 18, test1: 'test1', }] const result = Object.values([...current, ...new_data].reduce((acc, { categoryId, ...other }) => ({...acc, [categoryId]: { categoryId, ...other } }), {})); console.log(result);

You can use es6 spread operator to meet your requirement您可以使用 es6 扩展运算符来满足您的要求

  var current = [{
    categoryId: 18,
    id: 'fire_18',
    name: 'Servers',
    slugName: 'fire_18',
    test: 'test'
}]

var new_data = [{
    id: 'fire_18',
    categoryId: 18,
    name: 'Servers',
    slugName: 'fire_18'
}]

const results = new_data.map(item => {
    let newItem = { ...item };
    const currentMatchItem = current.find(c => c.categoryId == newItem.categoryId);

    if (currentMatchItem) {
        newItem = { ...currentMatchItem, ...newItem };
    }

    return newItem;
});

console.log(results);

I found this .我找到了这个 On your code it goes like that:在你的代码上是这样的:

 let current = [ { categoryId: 18, id: 'fire_18', test: 'test' }, { oldItem: "items that dont exist in new array should be deleted" } ] let new_data = [ { id: 'fire_18', categoryId: 18, test1: 'test1', }, { newItem: "new items should be added to final" } ] function merge(a, b, prop){ var reduced = a.filter(function(aitem){ return. b;find(function(bitem){ return aitem[prop] === bitem[prop]; }); }). return reduced;concat(b). } console,log(merge(current, new_data; "id") );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM