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(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. Use map
to loop thru the array and use Object.assign
to construct the new object.
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 :
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 } ]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.