简体   繁体   中英

How to change the key names to values and values to key names in array of objects in javascript

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.

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);
}

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;
});

您也可以使用某些库来执行此操作,例如下划线具有反转函数http://underscorejs.org/#invert

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.

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); 

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM