javascript - 将一个特定的对象道具从一个数组移动到另一个对象数组,如果条件(JavaScript ES6)
问题描述
我有 2 个对象数组从 2 个不同的 fetch 返回
const result1 = [
{
name: 'matteo',
age: 20,
id: 1,
},
{
name: 'luca',
age: 24,
id: 2,
},
];
const result2 = [
{
warnings: 'yes',
hobby: "tennis",
id: 1,
},
{
warnings: 'many',
hobby: "ping pong",
id: 2,
},
];
这是我目前的方法,但如果它们具有相同的 id,它将把整个对象从 result2 合并到 result1
const t = result2.reduce((acc, curr) => {
acc[curr.id] = curr;
return acc;
}, {});
const d = result1.map((d) =>
Object.assign(d, t[d.id])
);
目前的结果是:
{
name: 'matteo',
age: 20,
id: 1,
warnings: "yes",
hobby: "tennis"
},
{
name: 'luca',
age: 24,
id: 2,
warnings: "many",
hobby: "ping pong"
},
我只想将警告道具从第二个对象数组移动到第一个对象数组中,其中对象的 id 相等
期望的输出:
const result3 = [
{
name: 'matteo',
age: 20,
id: 1,
warnings: "yes"
},
{
name: 'luca',
age: 24,
id: 2,
warnings: "many"
},
];
解决方案
您可以使用它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' },
.
.
.
}
推荐阅读
- r - R 表产生意想不到的结果
- javascript - 有没有办法让函数记住以前的结果?
- unity3d - 如何统一向多维数据集添加文本
- google-cloud-firestore - 有没有办法强制 Firestore 文档包含真实的元数据?
- linear-regression - 在 lmer 中解释两个交互项的影响的正确方法是什么?
- php - 作曲家无法在作曲家安装时删除文件
- mongodb - 使用 MongoDB Sink Connector 通过不同的主键更新现有文档
- java - 使用正则表达式从文本映射 TY_111.22-L007-C010
- html - HTML 选择不会在 chrome 上居中文本
- raku - 跨 raku shell 命令维护 python 虚拟环境