[英]Sort an object of arrays in JavaScript
with an object like 与像
{
5: ['C','A','B'],
8: ['E','F','D']
}
I'm trying to sort the arrays of each key, while returning the entire object. 我正在尝试对每个键的数组进行排序,同时返回整个对象。 The above would come back looking like this:
上面的内容看起来像这样:
{
5: ['A','B','C'],
8: ['D','E','F']
}
I've tried lots of variations of 我尝试了许多变化
Object.keys(myObj).map(k => {
return { k: myObj[k].sort() };
}
But this puts a literal k
as each key instead of maintaining the keys from the original object. 但这会将文字
k
作为每个键,而不是维护原始对象的键。 Not to mention this also creates an array of objects since map
is returning an object for each key. 更不用说这还会创建一个对象数组,因为
map
为每个键返回一个对象。
Edit: 编辑:
I've found lots of "sort array of objects" - but not a "sort object of arrays" on SO - dupe and link if it already exists please. 我发现很多“对象的排序数组”-但不是SO上的“数组的排序对象”-复制并链接(如果已经存在)。
Try. 尝试。
const newSortedObj = Object.entries(yourObject).reduce((acc, [key, values]) => {
acc[key] = values.sort((a, b) => a.localeCompare(b));
return acc;
}, {})
Do consider the locale and the character casing when you do string sort
. 进行
string sort
时,请考虑语言环境和字符大小写。 Have a look at the local compare API 看一下本地比较API
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.