I'm looking for a way in javascript to transform this json to something else.
{
"John Doe": {
"place": "Amsterdam"
},
"Jane Doe": {
"place": "Paris"
}
}
To something like this:
{
{ "id": 0,
"name": "John Doe",
"place": "Amsterdam"
},
{ "id": 1,
"name": "Jane Doe",
"place": "Paris"
},
}
How can I achieve this with javascript?
CodePudding user response:
You can use Object.entries
to get key/value
pair and use map
method to transform the object into the new one.
const data = {
"John Doe": {
"place": "Amsterdam"
},
"Jane Doe": {
"place": "Paris"
}
}
const result = Object.entries(data).map(([key, value], index) => ({
id: index,
name: key,
place: value.place
}))
console.log(result)
CodePudding user response:
You can map the entries to objects. You can mix destructuring and object property shorthand to simplify this greatly.
Note: Order is not guaranteed when iterating through an object's keys.
const obj = {
"John Doe": { "place": "Amsterdam" },
"Jane Doe": { "place": "Paris" },
};
const list = Object.entries(obj)
.map(([name, { place }], id) =>
({ id, name, place }));
console.log(list);
.as-console-wrapper { top: 0; max-height: 100% !important; }