1

i have array of objects like this

[{
    "First Name": "fname",
    "Last Name": "lname"
}, {
    "Root cause": "root"
}, {
    "Comapany Name": "company"
}]

i want to convert the above array of objects into like this

 [{
    "fname": "First Name",
    "lname": "Last Name"
}, {
    "root": "Root cause"
}, {
    "company": "Comapany Name"
}]

please can anybody help me on this.

Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
Jeevan
  • 756
  • 13
  • 39

6 Answers6

0

This should do it

var arr = [ {"First Name":"fname", "Last Name":"lname"},
            {"Root cause":"root"},
            {"Comapany Name":"company"}
           ];            
var newArr = [];
for(var i = 0; i < arr.length; ++i) {
    var obj = {};
    for(key in arr[i]) {
        if (arr[i].hasOwnProperty(key)) {
            obj[arr[i][key]] = key;
        }
    }
    newArr.push(obj);
}
tpdietz
  • 1,358
  • 9
  • 17
0

You can use Object.keys to get an array of keys in an object. This can be used to access each value in the object.

For example:

var newArray = myArray.map(function(obj){
  var keys = Object.keys(obj);
  var newObj = {};

  keys.forEach(function(key){
      var newKey = obj[key];
      newObj[newKey] = key;
  });

  return newObj;
});
benbrunton
  • 980
  • 10
  • 18
0

You can also use some library to do that, for example underscore has an invert function http://underscorejs.org/#invert.

Lisa Gagarina
  • 693
  • 5
  • 7
0

This code doesn't create a new instance, it just inverts the keys in the same object:

var hash = { 'key1': 'val1', 'key2': 'val2' };

console.log('before', hash)

for (var key in hash) {
  hash[hash[key]] = key;
  delete hash[key];
}

console.log('after', hash)

This one creates a new object keeping the original unchanged:

var hash = { 'key1': 'val1', 'key2': 'val2' };

console.log('before', hash)

var newHash = {};

for (var key in hash) {
  newHash[hash[key]] = key;
}

console.log('new hash inverted', newHash)

You can create a function to reuse the code.

0

You can do it like this.

var arr1 =[{"First Name":"fname", "Last Name":"lname"},
{"Root cause":"root"},
{"Comapany Name":"company"}
]

var arr2=[];

for(var i=0; i<arr1.length; i++){
    
    var obj = {};
    var foo= arr1[i];
    for(var key in foo){
       obj[foo[key]]=key;
    }         
    arr2.push(obj);
}

console.log(arr2);
Vibhesh Kaul
  • 2,593
  • 1
  • 21
  • 38
0

Just iterate over all your array of objects and exchanges object values for object keys:

var a = [{"First Name": "fname", "Last Name": "lname"}, {"Root cause": "root"}, {"Comapany Name": "company"}];

a.forEach(function(o) {
    for (var key in o) {
        o[o[key]] = key;
        delete o[key];
    }
});

console.log(a);
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46