3 回答
TA贡献1836条经验 获得超5个赞
尝试这个:
const finalResult = {};
const data = {
"data": [
{
"persons": {
"Dupont nicolas": "President",
"George frimaolo": "engineer",
"Tiprana masilo": "football player"
}
},
{
"persons": {
"Balack martini": "author",
"Dupont nicolas": "Student",
"Joseph Allen": "dentist"
}
},
{
"persons": {
"Fred Samanta": "baker",
"Romero flagipi": "actor",
"Fred Samanta": "astronaut",
"Joseph Allen": "pilot",
"Anne Hedley": "teacher"
}
}
]
}
for (let i in data.data) {
for (let j in data.data[i].persons) {
finalResult[j] = finalResult[j] ? finalResult[j] : data.data[i].persons[j];
}
}
console.log(finalResult);
TA贡献1777条经验 获得超10个赞
使用reduce和Object.assign
const combine = (arr) =>
arr.reduce((acc, { persons }) => Object.assign(acc, persons), {});
const data = [
{
persons: {
"Dupont nicolas": "President",
"George frimaolo": "engineer",
"Tiprana masilo": "football player",
},
},
{
persons: {
"Balack martini": "author",
"Dupont nicolas": "Student",
"Joseph Allen": "dentist",
},
},
{
persons: {
"Fred Samanta": "baker",
"Romero flagipi": "actor",
"Fred Samanta": "astronaut",
"Joseph Allen": "pilot",
"Anne Hedley": "teacher",
},
},
];
console.log(combine(data))
TA贡献1796条经验 获得超7个赞
一个简单的Array.reduce应该可以实现你的目标。
const obj = {
// json data shown in your question
}
const result = obj.data.reduce(
(acc, cur) => ({
...cur.persons,
...acc,
}),
{}
);
添加回答
举报