How can I sort the keys inside the object that is inside an array?
So I have a json file that has this data:
[
{
"name": "AAA",
"age": 17,
"location": "US"
},
{
"age": 15,
"name": "BBB",
"location": "CA"
},
{
"location": "NZ",
"age": 10,
"name": "CCC"
}, ...
]
How can I possibly make the data like this:
[
{
"name": "AAA",
"age": 17,
"location": "US"
},
{
"name": "BBB",
"age": 15,
"location": "CA"
},
{
"name": "CCC",
"age": 10,
"location": "NZ"
}, ...
]
>Solution :
Here is how you can sort the props of each object.
mapthe array to modify its items- Use
Object.entriesto convert itsprop: valuepairs into an array so you could sort them - Convert them back to an object using
Object.fromEntries.
The advantage of using this approach is that you don’t need to know the prop names in advance.
const source = [
{
"name": "AAA",
"age": 17,
"location": "US"
},
{
"age": 15,
"name": "BBB",
"location": "CA"
},
{
"location": "NZ",
"age": 10,
"name": "CCC"
}
]
const sortedSource = source.map(item => {
return Object.fromEntries(
Object.entries(item).sort(([key1], [key2]) => {
return key1.localeCompare(key2);
})
)
});
const stringify = obj => JSON.stringify(obj, null, 2);
console.log(stringify(source), stringify(sortedSource));
https://jsbin.com/fiwuyecuco/edit?js,console