-1

My javascript object looks like the example below, I am wondering how I should write a swap function to change the element position in the object. For example, I want to swap two elements from position 1 to 2 and 2 to 1.

{
  element_name_1 : {
    //.. data
  }
  element_name_2 : {
    //.. data
  }
  element_name_3 : {
    //.. data
  }
  element_name_4 : {
    //.. data
  }
}

Now I want to swap element_name_2 with element_name_1.

directory
  • 3,093
  • 8
  • 45
  • 85
  • What do you want to swap, key or value? – Hassan Imam Sep 07 '17 at 12:59
  • Items in an object kind of have an order, you can see it with for(var key in obj) {...} , but I don't see why that would ever bother you and why you want to swap the order. Or is it the values you want to swap? – Emmanuel Delay Sep 07 '17 at 13:59

2 Answers2

1

As Miles points out, your code is probably broken and should use an array. I wouldn't use it, nor is it tested, but it is possible.

var data = {
  element_name_1: {},
  element_name_2: {},
  element_name_3: {},
  element_name_4: {}
}

console.log(data);

var swap = function(object, key1, key2) {
  // Get index of the properties
  var pos1 = Object.keys(object).findIndex(x => {
    return x === key1
  });
  var pos2 = Object.keys(object).findIndex(x => {
    return x === key2
  });

  // Create new object linearly with the properties swapped
  var newObject = {};
  Object.keys(data).forEach((key, idx) => {
    if (idx === pos1)
      newObject[key2] = object[key2];
    else if (idx === pos2)
      newObject[key1] = object[key1];
    else
      newObject[key] = object[key];
  });
  return newObject;
}

console.log(swap(data, "element_name_1", "element_name_2"));
Namaskar
  • 2,114
  • 1
  • 15
  • 29
-1

Have a look at the code, may this solve the problem

function swapFunction(source, destination) {
    var tempValu,
        sourceIndex;
    for ( i = 0; i < Arry.length; i++) {
        for (var key in Arry[i]) {
            Ti.API.info('key : ' + key);
            if (source == key) {
                tempValu = Arry[i];
                sourceIndex = i;
            }
            if (destination == key) {
                Arry[sourceIndex] = Arry[i];
                Arry[i] = tempValu;
                return Arry;
            }           
        }
    }
}

JSON.stringify(swapFunction("key_1", "key_3"));  // [{"key_3":"value_3"},{"key_2":"value_2"},{"key_1":"value_1"},{"key_4":"value_4"},{"key_5":"value_5"}]

Let me know if this works.

Good Luck & Cheers

Ashish Sebastian

A. A. Sebastian
  • 540
  • 1
  • 7
  • 19