[英]How to sort key/value objects in javascript?
Following How can I add a key/value pair to a JavaScript object? 以下如何将键/值对添加到JavaScript对象? and Best way to store a key=>value array in JavaScript?
和在JavaScript中存储key => value数组的最佳方法? , I built my Key/Value map (object).
,我建立了键/值映射(对象)。
And I build it like below where MyFunc
returns an array: 然后像下面的
MyFunc
返回数组那样构建它:
let MyMap = {}; // object
for(let i = 0; i < MyContainer.length; i++)
{
// create the key (id of current element) and set its value as array of elements (result from MyFunc)
await MyFunc(MyContainer[i]).then((response) => MyMap[MyContainer[i].id] = response);
}
MyMap
look like this: MyMap
如下所示:
MyMap =
{
1: [Object, Object, Object, …] // 13 elements
2: [Object, Object, Object, …] // 7 elements
3: [Object, Object, Object, …] // 4 elements
4: [Object]
5: [Object]
6: [Object, Object, Object, …] // 5 elements
7: [Object, Object, Object, …] // 9 elements
}
I would like to iterate my map (keys) but starting from the key that has the smallest value (The smallest array). 我想迭代我的地图(键),但要从具有最小值(最小数组)的键开始。
Therefore, I would like to: 因此,我想:
4
, and do stuff (has the smallest array: 1 element) 4
的元素,然后执行操作(具有最小的数组:1个元素) 5
, and do stuff 5
的元素,然后执行操作 3
3
6
6
1
and do stuff (has the largest array: 13 elements) 1
的元素并进行处理(具有最大的数组:13个元素) Now since myMap
is an object, then I can't sort it. 现在,由于
myMap
是一个对象,因此无法对其进行排序。
How can I accomplish this? 我该怎么做?
Eventually, you won't be able to use an Object because the order of the keys is not guaranteed . 最终,因为不能保证键的顺序,所以您将无法使用Object。
You can: 您可以:
Object.keys(obj)
to get the keys of your object as an Array
Object.keys(obj)
以Array
获取对象的键 Array
of objects of your structure, each item in the array being the key/value pair of your original object. Array
, Array
中的每个项目都是原始对象的键/值对。 Array
of objects based on the length of each item.value
within it. item.value
的长度item.value
对象Array
进行排序。 The item.value
in this case is your original object's values which are Array
s item.value
是原始对象的Array
值。 const obj = { "1": [1, 2, 3], "2": [1], "3": [1, 2], "4": [1, 2, 3, 4] }; // Transform object into a nested array // Each array item contains the value of a key of your original object, // which itself is an Array const arr = Object.keys(obj).reduce((arr, key) => { arr.push({ key: key, value: obj[key] }); return arr; }, []) // Sort the nested Array based on the length of each item const sortedArr = arr.sort((a, b) => a.value.length - b.value.length); console.log(sortedArr);
const obj = { "1": [1, 2, 3], "2": [1], "3": [1, 2], "4": [1, 2, 3, 4] }; const sortedArr = Object.keys(obj).reduce((arr, key) => { arr.push({ key: key, value: obj[key] }); return arr; }, []) .sort((a, b) => a.value.length - b.value.length) console.log(sortedArr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.