4 回答
TA贡献1811条经验 获得超5个赞
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)
TA贡献2003条经验 获得超2个赞
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贡献1799条经验 获得超8个赞
使用查找条目
Object.entries
destructuring
通过将键添加到累加器来减少当前对象推入结果数组
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贡献1810条经验 获得超4个赞
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]} ));
添加回答
举报