我有一个看起来像这样的对象:
{
"1": "Technology",
"2": "Startup",
"3": "IT",
}
我需要将它转换为一个看起来像这样的对象数组:
[
{id: 1, name: "Technology"},
{id: 2, name: "Startup"},
{id: 3, name: "IT"}
]
什么是最干净的&有效的方法吗?
答案 0 :(得分:9)
您可以将.map()
与Object.keys()
:
let data = {
"1": "Technology",
"2": "Startup",
"3": "IT",
};
let result = Object.keys(data)
.map(key => ({id: Number(key), name: data[key]}));
console.log(result);

有用的资源:
答案 1 :(得分:3)
假设您的对象实例名为obj
:
Object.keys(obj).reduce((acc, curr) => {
return [...acc, { id: curr, name: obj[curr] }]
}, [])
答案 2 :(得分:1)
琐碎的方式
var o = {
"1": "Technology",
"2": "Startup",
"3": "IT",
};
var arr = [];
for(var i in o) {
arr.push({
id: i,
number: o[i]
});
};
答案 3 :(得分:-1)
const words = {
told: 64,
mistake: 11,
thought: 16,
bad: 17
}
const results = []
Object.entries(words).map(val => results.push({
text: val[0],
value: val[1]
}))
console.log(results)