Move object element position in javascript

后端 未结 3 1008
旧巷少年郎
旧巷少年郎 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条回答
  • 2021-01-25 12:44

    Objects in JavaScript are essentially hash maps. Their properties don't have any ordering, per se. They are simply name value pairs.

    You are probably confusing objects with arrays, in which case ordering does indeed matter.

    0 讨论(0)
  • 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" : {},
    }
    
    0 讨论(0)
  • 2021-01-25 12:52

    JavaScript objects don't have ordering. You should use an array of objects instead.

    var arr = [
      { id: 'element1' },
      { id: 'element2' },
      { id: 'element3' }
    ]
    

    You could then reorder it something like:

    var first = arr.splice(0, 1);
    arr.push(first);
    

    Maybe you could then grab specific elements based on id:

    var out = arr.filter(function (el) {
      return el.id === 'element1';
    });
    
    0 讨论(0)
提交回复
热议问题