How can we custom sort JavaScript object keys?

后端 未结 3 385
太阳男子
太阳男子 2021-01-17 00:20

I am trying to custom sort a JavaScript object but not able to get how we can do this in a right way. Say I am having an object like

var test = {
  \'yellow\         


        
3条回答
  •  滥情空心
    2021-01-17 00:44

    May be you could change this using JSON.stringify()

    do like

    var json = {     "name": "David",     "age" : 78,     "NoOfVisits" : 4   };
    console.log(json);
    //outputs - Object {name: "David", age: 78, NoOfVisits: 4}
    //change order to NoOfVisits,age,name
    
    var k = JSON.parse(JSON.stringify( json, ["NoOfVisits","age","name"] , 4));
    console.log(k);
    //outputs - Object {NoOfVisits: 4, age: 78, name: "David"} 
    

    put the key order you want in an array and supply to the function. then parse the result back to json.

提交回复
热议问题