Changing the order of the Object keys…

后端 未结 11 2172
無奈伤痛
無奈伤痛 2020-11-27 07:21
var addObjectResponse = [{
    \'DateTimeTaken\': \'/Date(1301494335000-0400)/\',
    \'Weight\': 100909.090909091,
    \'Height\': 182.88,
    \'SPO2\': \'222.00000         


        
11条回答
  •  感动是毒
    2020-11-27 08:18

    I like the approved answer by Chamika Sandamal. Here's a simple function that uses their same logic with a little be of freedom to change the order as you need it.

    function preferredOrder(obj, order) {
        var newObject = {};
        for(var i = 0; i < order.length; i++) {
            if(obj.hasOwnProperty(order[i])) {
                newObject[order[i]] = obj[order[i]];
            }
        }
        return newObject;
    }
    

    You give it an object, and an array of the key names you want, and returns a new object of those properties arranged in that order.

    var data = {
        c: 50,
        a: 25,
        d: 10,
        b: 30
    };
    
    data = preferredOrder(data, [
        "a",
        "b",
        "c",
        "d"
    ]);
    
    console.log(data);
    
    /*
        data = {
            a: 25,
            b: 30,
            c: 50,
            d: 10
        }
    */
    

    I'm copying and pasting from a big JSON object into a CMS and a little bit of re-organizing of the source JSON into the same order as the fields in the CMS has saved my sanity.

提交回复
热议问题