gpt4 book ai didi

javascript - 根据键合并两个对象数组

转载 作者:行者123 更新时间:2023-12-02 23:06:08 27 4
gpt4 key购买 nike

我有两个数组:

数组1:

[
{ id: "abdc4051", date: "2017-01-24" },
{ id: "abdc4052", date: "2017-01-22" }
]

和数组 2:

[
{ id: "abdc4051", name: "ab" },
{ id: "abdc4052", name: "abc" }
]

我需要根据id合并这两个数组并得到:

[
{ id: "abdc4051", date: "2017-01-24", name: "ab" },
{ id: "abdc4052", date: "2017-01-22", name: "abc" }
]

如何在不迭代 Object.keys 的情况下做到这一点?

最佳答案

你可以这样做 -

let arr1 = [
{ id: "abdc4051", date: "2017-01-24" },
{ id: "abdc4052", date: "2017-01-22" }
];

let arr2 = [
{ id: "abdc4051", name: "ab" },
{ id: "abdc4052", name: "abc" }
];

let arr3 = arr1.map((item, i) => Object.assign({}, item, arr2[i]));

console.log(arr3);

<小时/>

如果 arr1arr2 的顺序不同,请使用以下代码:

let arr1 = [
{ id: "abdc4051", date: "2017-01-24" },
{ id: "abdc4052", date: "2017-01-22" }
];

let arr2 = [
{ id: "abdc4051", name: "ab" },
{ id: "abdc4052", name: "abc" }
];

let merged = [];

for(let i=0; i<arr1.length; i++) {
merged.push({
...arr1[i],
...(arr2.find((itmInner) => itmInner.id === arr1[i].id))}
);
}

console.log(merged);

如果 arr1arr2 顺序相同,则使用此选项

let arr1 = [
{ id: "abdc4051", date: "2017-01-24" },
{ id: "abdc4052", date: "2017-01-22" }
];

let arr2 = [
{ id: "abdc4051", name: "ab" },
{ id: "abdc4052", name: "abc" }
];

let merged = [];

for(let i=0; i<arr1.length; i++) {
merged.push({
...arr1[i],
...arr2[i]
});
}

console.log(merged);

关于javascript - 根据键合并两个对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46849286/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com