将数组转换为键/值对

时间:2017-02-03 05:55:42

标签: jquery arrays json

我已将嵌套循环中的不同值推送到对象中,结果如下:

obj = ["blue", 1, "red", 4, "yellow", 2, "green", 7];

但我希望它能像这样回归:

obj = [{"blue": 1}, {"red": 4}, {"yellow": 2}, {"green": 7}];

我是否必须手动构建该语法或者是否有更快的方法?

5 个答案:

答案 0 :(得分:2)

使用简单的for循环。



var obj = ["blue", 1, "red", 4, "yellow", 2, "green", 7];

var res = [];

for (var i = 0; i < obj.length; i += 2) {
  var o = {};
  o[obj[i]] = obj[i + 1];
  res.push(o);
}

console.log(res);
&#13;
&#13;
&#13;

使用Array.from()方法的ES6解决方案。

&#13;
&#13;
let obj = ["blue", 1, "red", 4, "yellow", 2, "green", 7];

console.log(Array.from({ length: obj.length / 2 }, (_, i) => ({ [obj[2 * i]]: obj[2 * i + 1] })));
&#13;
&#13;
&#13;

答案 1 :(得分:1)

使用for循环来获得结果,如

&#13;
&#13;
var obj = ["blue", 1, "red", 4, "yellow", 2, "green", 7];

var newObj = []
for(var i = 0; i < obj.length; i+=2) {
  var temp = {};
  temp[obj[i]] = obj[i + 1];
  newObj.push(temp);
  
}
console.log(newObj);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以使用此

var obj = ["blue", 1, "red", 4, "yellow", 2, "green", 7];
  var newObj = [];
  var itemValue,itemName = '';
  $(obj).each(function(index, item){
    if(index % 2 == 0){
      if(itemName != ''){
        var newObjEle = {};
        newObjEle[itemName] = itemValue;
        newObj.push(newObjEle);
      }
      itemName = item;
    }
    else{
        itemValue = item
    }
  })
  console.log(newObj);

Working fiddle

答案 3 :(得分:0)

一种方法是使用空JSON对象数组初始化结果,然后遍历它以填充对象。

&#13;
&#13;
var obj = ["blue", 1, "red", 4, "yellow", 2, "green", 7];

var result = Array.apply(null, Array(obj.length / 2)).map(i => ({}));
result.forEach((c, i, a) => (a[i][obj[2 * i]] = obj[2 * i + 1]));

console.log(result);
&#13;
&#13;
&#13;

答案 4 :(得分:0)

检查一下,

obj = ["blue", 1, "red", 4, "yellow", 2, "green", 7];
result = [];
for (i = 0; i < obj.length; i++) {
  if (i % 2 == 0) {
    temp = {};
    temp[obj[i]] = obj[i + 1];
    result.push(temp);
  }
}
console.log(result);

工作jsfiddle

试一试,它将解决您的问题。