从对象和数组创建一个对象数组

时间:2016-09-26 10:58:25

标签: javascript arrays for-loop

我有一个对象:

items =  {
    0: "foo",
    1: "bar",
    2: "baz"
};

和一个数组:

category = [
    "type1",
    "type2",
    "type3"
];

我想将这些与所需的输出合并:

newArray = [
    {type1:"foo"},
    {type2:"bar"},
    {type3:"baz"}
];

我以为我可以用以下的for循环完成它(虽然任何方法都可以):

var obj = {};
for (var i = 0; i < category.length; i++) { 
    obj [category[i]] = items[i];
    newArray.push(obj);
}

我实际得到的是:

[{"type1":"foo","type2":"bar","type3":"baz"},
 {"type1":"foo","type2":"bar","type3":"baz"},
 {"type1":"foo","type2":"bar","type3":"baz"}]

我猜每次i每次obj的所有实例都在迭代,但我如何修改以获得所需的输出?

https://jsfiddle.net/ormxq0y4/3/

6 个答案:

答案 0 :(得分:1)

您希望每次迭代都有一个新对象

for (var i = 0; i < category.length; i++) { 
   var obj = {};
   obj [category[i]] = items[i];
   newArray.push(obj);
}

答案 1 :(得分:1)

我想这应该这样做;

var items =  {
  0: "foo",
  1: "bar",
  2: "baz"
},
 category = [
  "type1",
  "type2",
  "type3"
],

 newArray = category.map((e,i) => ({[e]:items[i]}));
console.log(newArray)

答案 2 :(得分:0)

您可以尝试这样的事情 - &gt;

category.forEach(function (e,i) {
  var obj = {};
  obj[e] = items[i];
  newArray.push(obj);
});

答案 3 :(得分:0)

var items =  {
  0: "foo",
  1: "bar",
  2: "baz"
},
 category = [
  "type1",
  "type2",
  "type3"
];

var reformattedArray = category.map(function(obj, index){ 
   var rObj = {};
   rObj[obj] = items[index];
   return rObj;
});

console.log("reformattedArray", reformattedArray);

https://jsfiddle.net/s6ntL2eo/

答案 4 :(得分:0)

以下是我将如何做到这一点。但是,如果你只将KEY项作为数组的连接点进行中继,那么我的诚实意见是有点冒险的。还请记住,一个对象允许密钥是字符串或数字(这就是项目[+ key]的原因)。

&#13;
&#13;
var items =  {
  0: "foo",
  1: "bar",
  2: "baz"
};


var categories = [
  "type1",
  "type2",
  "type3"
];

var newArray = [];

categories.forEach(function (category, key) {
  if (items[+key]) {
    var tmpO = {};
    tmpO[category] = items[+key];
    newArray.push(tmpO);
  }
});

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

答案 5 :(得分:0)

您每次都不会制作单独的对象。而是将相同的对象推送三次,并将type1,type2,type3属性添加到此对象中。

只需将var obj = {}移动到循环中即可解决问题。

newArray = [];
 
items =  {
  0: "foo",
  1: "bar",
  2: "baz"
};

category = [
  "type1",
  "type2",
  "type3"
];

for (var i = 0; i < category.length; i++) { 
  var obj = {};
  obj[category[i]] = items[i];
  newArray.push(obj);
}

var title = document.getElementById("title");
title.innerHTML = JSON.stringify(newArray);

结果:[{"type1":"foo"},{"type2":"bar"},{"type3":"baz"}]