我想比较两个数组的每个对象。如果 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 。变得凌乱。 提前致谢:)
最佳答案
使用map
和find
。
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/