如何将 2 个对象合并为一个 - javascript

How to merge 2 objects into one - javascript

我需要帮助解决这个问题。我有两个对象: 输入:

obj1 =  [{name:A}, {name:B}, {name:C}...,]
obj2 =  [{value:1}, {value:2}, {value:3}...,]

我需要将这两个对象合二为一。 输出:

obj3 = [{A:1}, {B:2}, {C:3}...,]

有人知道如何将 obj 和 obj2 合并为一个吗?谢谢!

你可以这样做

const obj1 = [{name:'A'}, {name:'B'}, {name:'C'}];
const obj2 = [{value:1}, {value:2}, {value:3}];

const merged = Array.from({length:Math.min(obj1.length, obj2.length)}, (_,i) => {
  return { [obj1[i].name]: obj2[i].value };
});

console.log(merged);

如果命名一致,可以用索引映射。

const
    names = [{ name: 'A' }, { name: 'B' }, { name: 'C' }],
    values = [{ value: 1 }, { value: 2 }, { value: 3 }],
    result = names.map(({ name }, i) => ({ [name]: values[i].value }));

console.log(result);