As shown in the figure, I want to perform reverse order based on "1", "99", and "23"; it becomes
NvTC
May I ask the master who knows? Thank you
欢迎选择我的课程,让我们一起见证您的进步~~
1 var obj = { 2 '1':{ 3 val:'red' 4 }, 5 '99':{ 6 val:'yellow' 7 }, 8 '37':{ 9 val:'blue' 10 } 11 }; 12 13 function selirizeData(obj){ 14 var keys = Object.keys(obj).sort(function(a,b){ 15 return a-b; 16 }); 17 var newObj = {}; 18 keys.forEach(function(val){ 19 newObj[val] = obj[val]; 20 }); 21 console.log(keys); 22 console.log(newObj); 23 } 24 selirizeData(obj);
First use Object.keys() to get the key array of the object, then use the array sorting method to sort, then use the array's foreach method to loop through the array, sort the original object's data and write it to the new object.
var obj = { /* ..略.. */ } var res = Object.keys(obj).map(e => parseInt(e)).sort().map(e => obj[e]);
JS objects are unordered. Also:{
"11": "aaa"
}The 11 inside is a string.
Thoughts:forin所有的key到Array,排序Array.sort(),遍历Array,按顺序取值obj[key]
forin
key
Array
Array.sort()
obj[key]
var keys = []; for (var i in obj) { keys.push(i); } keys.sort(); for (var i = 0; i < keys.length; i++) { var key = keys[i]; console.log(obj[key]); }
In Object, data is stored in key => value pairs, so there is no order problem
First use Object.keys() to get the key array of the object, then use the array sorting method to sort, then use the array's foreach method to loop through the array, sort the original object's data and write it to the new object.
JS objects are unordered.
Also:
{
}
The 11 inside is a string.
Thoughts:
forin
所有的key
到Array
,排序Array.sort()
,遍历Array
,按顺序取值obj[key]