[英]Sort keys of array of objects in Javascript
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.
如果您绝对需要保证顺序,我相信建议是使用Map或转换为数组。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.