1 回答
TA贡献1887条经验 获得超5个赞
您可以使用它map来创建一个新数组,并find获取具有匹配 id 的任何警告:
let result1 = [
{ id: 1, name: 'a', age: 1 },
{ id: 2, name: 'b', age: 2 },
{ id: 3, name: 'c', age: 3 },
{ id: 4, name: 'd', age: 4 }
];
let result2 = [
{ id: 1, hobby: 'aa', warnings: 'aaa' },
{ id: 2, hobby: 'bb', warnings: 'bbb' },
{ id: 4, hobby: 'dd', warnings: 'ddd' }
];
let includeWarnings = (data, warningsArr) => data.map(obj => {
// `w` will be undefined if no matching warning is found
let w = warningsArr.find(warn => warn.id === obj.id);
// Return all the data in `obj`, and the "warnings" property
// of `w` if `w` is defined
return { ...obj, ...(w ? { warnings: w.warnings } : {}) };
});
console.log(includeWarnings(result1, result2));
请注意,如果您的数据格式是在考虑映射的情况下构建的,那么您的情况可能会更好id:
let result1 = {
id1: { name: 'name1', age: 1 },
id2: { name: 'name2', age: 2 },
.
.
.
}
let result2 = {
id1: { hobby: 'hobby1', warnings: 'warnings1' },
id2: { hobby: 'hobby2', warnings: 'warnings2' },
.
.
.
}
添加回答
举报