0

index array.

var index = ['a','b','c','d'];

Index array can have any number of items.

Result is an associative array with keys as same as index items:

result = [{ b:'Val1', c:'Val2', a:'Val3', d:'Val4' },{ b:'Val5', c:'Val6', a:'Val7', d:'Val8' }];

I have to create another array with keys in same order as of index array.

finalRes = [{ a:'Val3', b:'Val1', c:'Val2', d:'Val4' },{ a:'Val7', b:'Val5', c:'Val6', d:'Val8' }];

Any help will be appreciated. Thanks.

Pramod
  • 2,644
  • 6
  • 27
  • 39
Gautam Kumar
  • 881
  • 2
  • 12
  • 33

3 Answers3

1

Properties order in javascript objects is not guaranteed. If you want to specify an order for the key, you have to keep your ordered array of keys as well as the generated array.

ECMAScript Third Edition:

4.3.3 Object An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.

Source: Does JavaScript Guarantee Object Property Order?

Community
  • 1
  • 1
link
  • 1,646
  • 12
  • 21
0

let's see..

var index = ['a','b','c','d'];
result = [{ b:'Val1', c:'Val2', a:'Val3', d:'Val4' },{ b:'Val5', c:'Val6', a:'Val7', d:'Val8' }];

finalRes = [{ a:'Val3', b:'Val1', c:'Val2', d:'Val4' },{ a:'Val7', b:'Val5', c:'Val6', d:'Val8' }];

Final result can be created with a loop;

var finalRes = [];
for (var l=0; l<result.length; l++) {
  var res = {};
  for(var x=0; x<index.length; x++) {
     var i = index[x]; //i is the index value..
     res[i] = result[l][i];
  }

  finalRes[l] = res;
}

I believe this should work..

Popsyjunior
  • 175
  • 10
0

Here is a perfect solution what you exactly wanted: Tested here jsfiddle. See comments for Explanation.

var index = ['a','b','c','d'];
result = [{ b:'Val1', c:'Val2', a:'Val3', d:'Val4' },{ b:'Val5', c:'Val6', a:'Val7', d:'Val8' }];

var finalRes = [];

for (var i = 0; i<result.length; i++){
    //We get each slice of result array here
    //Lets begin a fresh array of this particular array
    thisArray = [];

    for (var j = 0; j<index.length; j++){
        //Now Preparing the particular Array
        var key = index[j]; //Key of Index Array
        thisArray[key] = result[i][key]
        // What we did just before is:
        // We created an Element Inside this Particular Array with reference of index and value of result
    }

    finalRes.push(thisArray);

}
console.log(finalRes); //Required Array
console.log(finalRes[0]["a"]); //Checking Elements

Watch Out!

 Caution: The finalRes is NOT NUMERIC. You can't refer it like: finalRes[0][0]
tika
  • 6,177
  • 2
  • 44
  • 78