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
巴扎黑2017-05-19 10:12:41
天蓬老师2017-05-19 10:12:41
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.
伊谢尔伦2017-05-19 10:12:41
var obj = { /* ..略.. */ }
var res = Object.keys(obj).map(e => parseInt(e)).sort().map(e => obj[e]);
淡淡烟草味2017-05-19 10:12:41
JS objects are unordered.
Also:
{
"11": "aaa"
}
The 11 inside is a string.
淡淡烟草味2017-05-19 10:12:41
Thoughts:forin
所有的key
到Array
,排序Array.sort()
,遍历Array
,按顺序取值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]);
}