4 回答

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超5個(gè)贊
forEach是數(shù)組的方法,同時(shí)你oldObj是對(duì)象
首先你必須將它轉(zhuǎn)換為數(shù)組,這里我們可以做的是將對(duì)象轉(zhuǎn)換為鍵值對(duì)數(shù)組
使用 withmap可以使代碼更短
const oldObj = {
Georgia: {
notes: "lorem ipsum",
lat: "32.1656",
long: "82.9001",
},
Alabama: {
notes: "lorem ipsum",
lat: "32.3182",
long: "86.9023",
},
}
const res = Object.entries(oldObj).map(([name, obj]) => ({ name, ...obj }))
console.log(res)

TA貢獻(xiàn)2003條經(jīng)驗(yàn) 獲得超2個(gè)贊
const oldObj = {
Georgia : {
notes: "lorem ipsum",
lat: "32.1656",
long: "82.9001"
},
Alabama : {
notes: "lorem ipsum",
lat: "32.3182",
long: "86.9023"
}
}
const desireArray = Object.keys(oldObj).map((key) => ({ name: key, ...oldObj[key] }));
解釋一下
const keys = Object.keys(oldObj);
const desireArray = keys.map((key) => {
return {
name: key,
notes: oldObj[key].notes,
lat: oldObj[key].lat,
long: oldObj[key].long
}
});

TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超8個(gè)贊
使用查找條目
Object.entries
destructuring
通過(guò)將鍵添加到累加器來(lái)減少當(dāng)前對(duì)象推入結(jié)果數(shù)組
const oldObj = {
? ? Georgia : {
? ? ? ? notes: "lorem ipsum",
? ? ? ? lat: "32.1656",
? ? ? ? long: "82.9001"
? ? },
? ? Alabama : {
? ? ? ? notes: "lorem ipsum",
? ? ? ? lat: "32.3182",
? ? ? ? long: "86.9023"
? ? }
};
const result = Object.entries(oldObj).reduce((acc, curr) => {
? ? const [key, val] = curr;
? ??
? ? acc.push({
? ? ? ? name: key,
? ? ? ? ...val
? ? });
? ? return acc;
}, []);
console.log(result);

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊
const oldObj = {
Georgia : {
notes: "lorem ipsum",
lat: "32.1656",
long: "82.9001"
},
Alabama : {
notes: "lorem ipsum",
lat: "32.3182",
long: "86.9023"
}
};
function convertObjToArr(obj) {
let result = [];
for(let key in obj) {
result.push({name: key, ...obj[key]});
}
return result;
}
console.log(convertObjToArr(oldObj));
或嘗試其他簡(jiǎn)單的解決方案
return Object.keys(obj).map(item => ( {name: item, ...obj[item]} ));
添加回答
舉報(bào)