How can we custom sort JavaScript object keys?

后端 未结 3 383
太阳男子
太阳男子 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:32

    JavaScript objects are hashes and therefore inherently un-ordered. You cannot make an object with properties in any given order. If you are receiving an ordering when you enumerate the keys, it is purely coincidental, or better said, an implementation detail of the JavaScript engine.

    You'd have to use an array of objects to achieve something like what you want to do.

    In other words, it is not possible with the data structure you have chosen.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-17 00:52

    You could use Map()

    A Map object iterates its elements in insertion order

    var arr = ['red', 'green', 'blue', 'yellow'];
    
    var map = new Map();
    
    arr.forEach(function(val, index) {
      var obj = {};
      obj[val] = [];
      map.set(index, obj)
    });
    
    console.log(map)

    0 讨论(0)
提交回复
热议问题