我想合并2个数组来创建new,它们具有基于key但无法实现的更新值。我正在寻找一种更简单的解决方案,采用es6 / es7方法。
let selectedID = [
{
"id": 7,
"selected": true
},
{
"id": 1,
"selected": true
}
];
let baseID = [
{
"id": 7,
"selected": false
},
{
"id": 12,
"selected": false
},
{
"id": 13,
"selected": false
},
{
"id": 1,
"selected": false
},
{
"id": 9,
"selected": false
},
{
"id": 10,
"selected": false
}
];
const op = baseID.map( b => {
return selectedID.map( f => {
if(f.id === s.id) {
return f;
} else {
return b;
}
});
});
console.log(op);
但它返回一个项目数组,每个项目都是2个对象的数组。
[[
{id: 7, selected: true}
{id: 7, selected: false}
,[],...]
预期产出:
[{
"id": 7,
"selected": true
},
{
"id": 12,
"selected": false
},
{
"id": 13,
"selected": false
},
{
"id": 1,
"selected": true
},
{
"id": 9,
"selected": false
},
{
"id": 10,
"selected": false
}
]
答案 0 :(得分:1)
您可以find
使用map
来查找selectedID
数组:
let selectedID = [
{
id: 7,
selected: true
},
{
id: 1,
selected: true
}
];
let baseID = [
{
id: 7,
selected: false
},
{
id: 12,
selected: false
},
{
id: 13,
selected: false
},
{
id: 1,
selected: false
},
{
id: 9,
selected: false
},
{
id: 10,
selected: false
}
];
const op = baseID.map(
item => selectedID.find(selectedItem => item.id === selectedItem.id) || item
);
console.log(op);