如何在javascript

时间:2016-05-20 14:27:18

标签: javascript arrays node.js underscore.js

我有像这样的对象

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

我想将上面的对象数组转换成这样的

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

请有人帮我这个。

6 个答案:

答案 0 :(得分:0)

这应该这样做

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

答案 1 :(得分:0)

您可以使用Object.keys获取对象中的键数组。这可用于访问对象中的每个值。

例如:

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

此代码不会创建新实例,只会反转同一对象中的键:

&#13;
&#13;
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)
&#13;
&#13;
&#13;

这个创建一个新对象,保持原始状态不变:

&#13;
&#13;
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)
&#13;
&#13;
&#13;

您可以创建一个函数来重用代码。

答案 4 :(得分:0)

你可以这样做。

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

答案 5 :(得分:0)

只需遍历所有对象数组并交换对象键的对象值:

   {
   "name":"app-name",
   "version":"0.0.0",
   "private":true,
   "scripts":{
      "start":"node ./bin/www"
   },
   "description":"descrt",
   "author":{
      "name":"myname",
      "email":"myemail@smtpserver.com"
   },
   "dependencies":{
      "body-parser":"~1.8.1",
      "cookie-parser":"~1.3.3",
      "debug":"~2.0.0",
      "express":"~4.9.0",
      "jade":"~1.6.0",
      "morgan":"~1.3.0",
      "request":"^2.72.0",
      "serve-favicon":"~2.1.3",
      "stylus":"0.42.3"
   }
}