Move object element position in javascript

后端 未结 3 1012
旧巷少年郎
旧巷少年郎 2021-01-25 12:13

I\'m trying to find a way to move an object element to a specific position.

For example, I\'ve this object :

{
    \"element1\" : {} // object,
    \"el         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-25 12:50

    Here's my code for doing that logic. Thanks!

    function _moveElementObject(object, from, to) {
        var newObjects = [];
        var newObject = {};
        var oldObject = {};
        var firstObject = {};
        var lastObject = {};
        var toMoveKey = "";
        var toMoveValue;
        oldObject = object;
        var objLength = _countProperties(oldObject);
        var keyNo = 1;
        for (var key in oldObject) {
            if (keyNo == from) {
                toMoveKey = key;
                toMoveValue = oldObject[key];
            }
            keyNo++;
        }
        console.log(oldObject);
    
        keyNo = 1;
        for (var key in oldObject) {
            if (keyNo < to) {
                firstObject[key] = oldObject[key];
                newObject[key] = firstObject[key];
            }
            keyNo++;
        }
        console.log(firstObject);
    
        keyNo = 1;
        for (var key in oldObject) {
            if (to <= objLength) {
                lastObject[key] = oldObject[key];
            }
            keyNo++;
        }
        delete lastObject[toMoveKey];
        newObject[toMoveKey] = toMoveValue;
    
        for (var key in lastObject) {
            newObject[key] = lastObject[key];
        }
        console.log(newObject);
        console.log("push");
        return newObject;
    }
    
    var sampleObj = {
        "element1" : {} // object,
        "element2" : {},
        "element3" : {}
    };
    
    _moveElementObject(sampleObj,3,1);
    
    // output object,
    {
        "element3" : {},
        "element1" : {}, 
        "element2" : {},
    }
    

提交回复
热议问题