JS object property name sort

Problem, object properties sorted by name, such as:

var data = { A:[], D:[], B:{} }

Adjusted = "

var data = { A:[], B:[], D:{} }

method one:

for, in, fieldname saved into an array, sort, then save the new value of the original object to sort objects according to the order

var arr=[];
for(var key in data){
    arr.push(key)
}
arr = arr.sort()
var newData={}
for(var i in arr){
    var itemKey = arr[i]
    newData[itemKey] = data[itemKey]
}

Method Two -ES6:

var newData = {};
Object.keys(data).sort().map(key => {
  newData[key]=s[key]
})

 

Guess you like

Origin www.cnblogs.com/Cailf/p/11718434.html