-
四季花海
forEach是数组的方法,同时你oldObj是对象首先你必须将它转换为数组,这里我们可以做的是将对象转换为键值对数组使用 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)
-
湖上湖
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 }});
-
守着星空守着你
使用查找条目Object.entriesdestructuring通过将键添加到累加器来减少当前对象推入结果数组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);
-
慕莱坞森
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));或尝试其他简单的解决方案 return Object.keys(obj).map(item => ( {name: item, ...obj[item]} ));