我有2个具有不同对象的数组,但是我需要某种map函数将2个数组映射到newArray。 newArray具有与arr1相同的对象类型。
let arr = [{Id: 1, Name:'test'}, {Id: 2, Name:'test2'}]
let secondarr = [{value:'test'}, {value:'test3'}]
const newArray = [{Id: 1, Name: 'test'}, {Id: null, value: 'test3'}];
arr.forEach(element => {
let exists = false;
secondarr.forEach(i => {
if(i.value === element.Name) {
exists = true;
}
});
if(exists) {
secondarr = secondarr.filter(l => l.value !== element.Name);
}
if(!exists) {
arr = arr.filter(l => l.Name !== element.Name);
}
});
secondarr.forEach(element => {
const newObj = {Id: null, Name: element.value};
arr.push(newObj);
});
答案 0 :(得分:0)
您可以使用map
来走arr2并使用find
来获取匹配的元素。
const arr1 = [{Id: 1, Name:'test'}, {Id: 2, Name:'test2'}]
const arr2 = [{value:'test'}, {value:'test3'}]
const newArray = arr2.map(x => {
// we search for the matching element.
const item = arr1.find(obj => obj.Name === x.value)
// if item exists get item, else create a new one
return item ? item : { Id: null, Name: x.value }
});
console.log(JSON.stringify(newArray))
输出
[{"Id":1,"Name":"test"},{"Id":null,"Name":"test3"}]