这里我们使用 for... in 遍历
const data = {
2: "笨笨",
5: "小黑",
3: "阿呆",
};
let newData = new Array;
for (var i in data) {
var json = {};
if (data[i] != "") {
json.id = i;
json.name = data[i];
newData.push(json);
}
}
console.log(newData)
// newData = [
// {id:'2',name: "笨笨"},
// {id:'5',name: "小黑"},
// {id:'3',name: "阿呆"}
// ];
打印:
将上面得到的数组转换为对象,这里使用了map数组遍历,如:
newData = [
{id:'2',name: "笨笨"},
{id:'5',name: "小黑"},
{id:'3',name: "阿呆"}
];
let newArrs = new Object();
newData.map((item) => {
newArrs[item.id] = item.name;
});
console.log(newArrs)
// const data = {
// 2: "笨笨",
// 5: "小黑",
// 3: "阿呆",
// };
打印: