进行一些数据转换练习并陷入困境。我有一个对象,我想要转换为from (starting)
- > to (expected ending)
输出如下所述。我尝试使用Array.reduce
和Object.assign
来保持输出纯净。但我无法让它正常工作。
/**
* from (starting): {topic: {id: 2}, products: {id: 3}}
* to (expected ending): {topic: 2, products: 3}
*/
const starting = {topic: {id: 2}, products: {id: 3}};
const ending = Object.keys(starting).reduce((p, key) => {
if(!p[key]) p[key] = key;
return Object.assign(p[key], starting[key].id);
}, {})
答案 0 :(得分:7)
您可以使用reduce
,只需记住在每次迭代后返回起始对象。
function convert(start) {
return Object.keys(starting).reduce((o, key) => {
o[key] = start[key].id;
return o;
}, {});
}
const starting = {topic: {id: 2}, products: {id: 3}};
console.log(convert(starting));

答案 1 :(得分:3)
试试这个:
var starting = {topic: {id: 2}, products: {id: 3}};
var ending = Object.keys(starting).reduce((p, key) => {
p[key] = starting[key].id;
return p;
}, {})
这将创建一个新对象,因此不需要Object.assign
等来保持输出纯净。
答案 2 :(得分:2)
我认为reduce()
不是正确的工具。
尝试使用starting
代替forEach()
的密钥:
const starting = {topic: {id: 2}, products: {id: 3}};
const ending = {};
Object.keys(starting).forEach(p => ending[p] = starting[p].id);
console.log(ending);
答案 3 :(得分:2)
纯函数解决方案需要您在每次迭代时返回一个新对象:
function convert(start) {
return Object.keys(starting).reduce((o, key) =>
Object.assign({}, {
[key]: start[key].id
}, o), {});
}
const starting = {topic: {id: 2}, products: {id: 3}};
console.log(convert(starting));

使用对象传播使它更清洁:
function convert(start) {
return Object.keys(starting).reduce((o, key) => ({
...o,
[key]: start[key].id
}), {});
}
const starting = {topic: {id: 2}, products: {id: 3}};
console.log(convert(starting));