[英]How can I convert this object of objects into an array of objects?
How can I convert this object: 如何转换此对象:
var json = {
"user3" : {
"id" : 1
},
"user1" : {
"id" : 3
},
"user2" : {
"id" : 6
}
}
to this array: 到这个数组:
var json = [{
"name": "user1",
"id": 3
}, {
"name": "user2",
"id": 6
}, {
"name": "user3",
"id": 1
}];
Can someone tell me? 有人可以告诉我吗? Or how can I sort an object like the first example? 或者如何像第一个示例那样对对象进行排序?
Try 尝试
const src = {
"user3" : {
"id" : 1
},
"user1" : {
"id" : 3
},
"user2" : {
"id" : 6
}
}
const out = Object.keys(src).map((key) => ({name: key, id: src[key].id}))
You can use Object.keys() and Array.prototype.reduce() to iterate over the object items and create an array out of the single items. 您可以使用Object.keys()和Array.prototype.reduce()遍历对象项,并根据单个项创建一个数组。
Object.keys(json).reduce((items, username) => {
const user = json[username];
return items.concat({
name: username,
id: user.id
});
}, []);
You can use Object.entries
to convert the object into an array. 您可以使用Object.entries
将对象转换为数组。 Use map
to loop thru the array and use Object.assign
to construct the new object. 使用map
遍历数组,并使用Object.assign
构造新对象。
var json = { "user3": { "id": 1 }, "user1": { "id": 3 }, "user2": { "id": 6 } } var result = Object.entries(json).map(([k, o]) =>Object.assign(o, {name: k})); console.log(result);
An alternative approach, using a for-in loop : 一种替代方法,使用for-in循环 :
const json = {
"user3": {
"id": 1
},
"user1": {
"id": 3
},
"user2": {
"id": 6
}
}
const result = [];
for (const prop in json) {
result.push({ "name": prop, "id": json[prop].id });
}
console.log(result);
Will provide: 会提供:
[ { name: 'user3', id: 1 },
{ name: 'user1', id: 3 },
{ name: 'user2', id: 6 } ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.