gpt4 book ai didi

javascript - 使用 Object.assign() 组合两个对象数组?

转载 作者:行者123 更新时间:2023-12-03 03:53:53 24 4
gpt4 key购买 nike

我不太确定为什么 Object.assign() 没有提供预期的结果(请参阅底部的注释部分)。我是否缺少该功能的某些内容,或者是否有更干净的方法来执行此操作?

下面的代码到达带有变量“i”的 for 循环,但没有到达带有变量“x”的第二个 for 循环。

    const array_1 = [{property1:'a',property2:'b'}, {property1:'c',property2:'d'}];
const array_2 = [{property3:'w',property4:'x'}, {property3:'y',property4:'z'}];

const CombineArrays = (array_1, array_2) => {
let combined_array = [];
for (let i = 0; i < array_1.length; i++) {
for (let x = 0; x < array_2.length; x++) {
const newObj = Object.assign(array_1[i], array_2[x]);
combined_array.push(newObj);
}
}
return combined_array;
};

const result = CombineArrays(array_1, array_2);
console.log(result);


// expected result = [
// {property1:'a',property2:'b', property3:'w',property4:'x'},
// {property1:'a',property2:'b', property3:'y',property4:'z'},
// {property1:'c',property2:'d', property3:'w',property4:'x'},
// {property1:'c',property2:'d', property3:'y',property4:'z'}
// ]
// current result = [
// { property1: 'a', property2: 'b', property3: 'y', property4: 'z' },
// { property1: 'a', property2: 'b', property3: 'y', property4: 'z' },
// { property1: 'c', property2: 'd', property3: 'y', property4: 'z' },
// { property1: 'c', property2: 'd', property3: 'y', property4: 'z' }
// ]

最佳答案

您可以使用 ... 扩展运算符合并对象。然后你就得到了你想要的结果,因为你没有覆盖原始数组。

const array_1 = [{property1:'a',property2:'b'}, {property1:'c',property2:'d'}];
const array_2 = [{property3:'w',property4:'x'}, {property3:'y',property4:'z'}];

const CombineArrays = (array_1, array_2) => {
let combined_array = [];
for (let i = 0; i < array_1.length; i++) {
for (let x = 0; x < array_2.length; x++) {
const newObj = {...array_1[i], ...array_2[x]};
combined_array.push(newObj);
}
}
return combined_array;
};

const result = CombineArrays(array_1, array_2);
console.log(result);

关于javascript - 使用 Object.assign() 组合两个对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59735378/

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