Changing the order of the Object keys…

后端 未结 11 2136
無奈伤痛
無奈伤痛 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:15

    I wrote this small algorithm which allows to move keys, it's like jQuery .insertAfter() method. You have to provide:

    //currentKey: the key you want to move
    //afterKey: position to move-after the currentKey, null or '' if it must be in position [0]
    //obj: object
    
    
    function moveObjectElement(currentKey, afterKey, obj) {
        var result = {};
        var val = obj[currentKey];
        delete obj[currentKey];
        var next = -1;
        var i = 0;
        if(typeof afterKey == 'undefined' || afterKey == null) afterKey = '';
        $.each(obj, function(k, v) {
            if((afterKey == '' && i == 0) || next == 1) {
                result[currentKey] = val; 
                next = 0;
            }
            if(k == afterKey) { next = 1; }
            result[k] = v;
            ++i;
        });
        if(next == 1) {
            result[currentKey] = val; 
        }
        if(next !== -1) return result; else return obj;
    }
    

    Example:

    var el = {a: 1, b: 3, c:8, d:2 }
    el = moveObjectElement('d', '', el); // {d,a,b,c}
    el = moveObjectElement('b', 'd', el); // {d,b,a,c}
    

提交回复
热议问题