javascript - 比较和更改两个对象数组

标签 javascript arrays object ecmascript-6

我想比较两个数组的每个对象。如果 array1 的属性名称与 array2 的属性名称匹配,则将 array2 的值​​从 array1 更改。

let array1 = [{
        name: 'test1',
        values: ['a', 'b', 'c']
    },
    {
        name: 'test2',
         values: ['w,','q','q' ]
    }
]

let array2 = [{
        name: 'test1',
        items: '...',
        settings: '...',
        values: []
    },
    {
        name: 'test9',
        items: '...',
        settings: '...',
        values: []
    },

    {
        name: 'test10',
        items: '...',
        settings: '...',
        values: []
    },

    {
        name: 'test2',
        items: 'test2',
        settings: '...',
        values: []
    },
]

预期从 array2 返回一个新数组集 -

let array2New = [{
            name: 'test1',
            items: '...',
            settings: '...',
            values: ['a', 'b', 'c']
        },
        {
            name: 'test9',
            items: '...',
            settings: '...',
            values: []
        },

        {
            name: 'test10',
            items: '...',
            settings: '...',
            values: []
        },

        {
            name: 'test2',
            items: 'test2',
            settings: '...',
            values: ['w,','q','q' ]
        }
    },
]

我尝试在 map 中使用嵌套 map 。变得凌乱。 提前致谢:)

最佳答案

使用mapfind

let array1 = [{name:'test1',values:['a','b','c']},{name:'test2',values:['w,','q','q']}];
let array2 = [{name:'test1',items:'...',settings:'...',values:[]},{name:'test9',items:'...',settings:'...',values:[]},{name:'test10',items:'...',settings:'...',values:[]},{name:'test2',items:'test2',settings:'...',values:[]},];

const res = array2.map(e => {
  let found = array1.find(({ name }) => name == e.name);
  if (found) e.values = found.values;
  return e;
});

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

关于javascript - 比较和更改两个对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56473156/

相关文章:

javascript - 在文档就绪 javascript 之外使用全局变量?

java - Object类中的hashCode()方法是如何实现的?

C++:如果 protected ,为什么在派生类内部无法访问基对象

javascript - 如何获取键值,无论它位于数组中的哪个位置

c++ - 删除现有指针数组的值,然后将新值分配给指针数组

python - 具有灵活 dtype 的 NumPy 数组可以与 == 进行比较,但不能与 np.equal 进行比较

javascript - 载入div后执行脚本

javascript - 在Google Maps v3中如何设置带有点的折线,这些点用粗点链接线

javascript - 在不同层次结构级别的两个 React 组件之间建立链接的好方法是什么?

c++ - 如何在 C++ 中将数组类型衰减为 const 指针类型?