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,
}),
{}
);
添加回答
舉報