I have array of objects which are not alphbatically sorted. I want to sort these key names. Is there any way to do this?
const artists = [ {name: "Tupac", year: 1996, age: 25}, {name: "Jayz", year: 2021, age: 48} ] // Looking for Output like this const artists = [ {age: 25, name: "Tupac", year: 1996}, {age: 48, name: "Jayz", year: 2021} ]
The following might work in practice. But there are caveats . If you absolutely need to guarantee the order I believe the advice is to use Map or convert to an array.
const artists = [ {name: "Tupac", year: 1996, age: 25}, {name: "Jayz", year: 2021, age: 48} ]; const sort_object_keys = (object) => Object.keys(object).sort().reduce( (acc, val) => Object.assign(acc, { [val]: object[val] }), {} ); const result = artists.map(sort_object_keys); console.log(result);
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.