我有2个objets a
和b
定义如下:
a = {
1:3,
2:5,
3:1,
}
b = {
1:{name:"Bob"},
2:{name:"John"},
3:{name:"Alice"}
}
我想要获得的是以下对象c
定义为
c = {
"Bob":3,
"John":5,
"Alice":1
}
因此创建一个使用b [key] .name作为c [key]和一个[key]作为值。
到目前为止我尝试的是
const mapAandB = (a, b) => {
let finalObject = [];
Object.keys(b).forEach(key => {
return finalOdds.push({ [b[key].name]: a[key] });
});
return finalOdds;
};
但结果是
c = [
0:{Bob:3},
1:{John: 5},
2:{Alice:1}
]
如果您有任何建议......
答案 0 :(得分:5)
您可以使用Array#reduce将名称和值收集到对象中:
const a = {"1":3,"2":5,"3":1}
const b = {"1":{"name":"Bob"},"2":{"name":"John"},"3":{"name":"Alice"}}
const result = Object.keys(a).reduce((r, key) => {
r[b[key].name] = a[key];
return r;
}, {});
console.log(result);
或者您可以使用Array#map创建一系列对象,并使用Object#assign和spread将它们合并为一个:
const a = {"1":3,"2":5,"3":1}
const b = {"1":{"name":"Bob"},"2":{"name":"John"},"3":{"name":"Alice"}}
const result = Object.assign(...Object.keys(a).map((key) => ({ [b[key].name]: a[key] })));
console.log(result);
答案 1 :(得分:1)
试试这个解决方案。如果您想获取对象而不是数组,只需将结果添加到Object.assign(...result)
const a = {
1:3,
2:5,
3:1,
}
const b = {
1:{name:"Bob"},
2:{name:"John"},
3:{name:"Alice"}
}
const mapAandB = (a, b) => Object.keys(a).map(key => ({[b[key].name]: a[key]}));
console.log(mapAandB(a,b));