Javascript合并一个对象和一个数组

时间:2014-10-30 09:32:57

标签: javascript arrays object

我的问题是合并一个对象和一个对象数组。

这是我的目标:

{

  model1: ["model1-coupe", "model1-hatchback", "model1-cabriolet"],
  model2: ["model2-coupe","model12-hatchback","model2-cabriolet"],
  model3: ["model3-coupe","model4-hatchback","model4-cabriolet"]

}

这是我的对象数组:

[
    {image: "/path/to/image/model1.jpg"},
    {image: "/path/to/image/model2.jpg"},
    {image: "/path/to/image/model3.jpg"}
]

我想将它们合并为:

[
    {
        image: "/path/to/image/model1.jpg",
        model1: ["model1-coupe", "model1-hatchback", "model1-cabriolet"]
    },

    {
        image: "/path/to/image/model2.jpg",
        model2: ["model2-coupe", "model2-hatchback", "model2-cabriolet"]
    },

    {
        image: "/path/to/image/model3.jpg",
        model3: ["model3-coupe", "model3-hatchback", "model3-cabriolet"]
    }
]

我该怎么做?我可以使用JavaScript或Underscore。

提前致谢

编辑:看看合并结果实际如何:

[
    {
        image: "/path/to/image/model1.jpg",
        cars: ["model1-coupe", "model1-hatchback", "model1-cabriolet"]
    },

    {
        image: "/path/to/image/model2.jpg",
        cars: ["model2-coupe", "model2-hatchback", "model2-cabriolet"]
    },

    {
        image: "/path/to/image/model3.jpg",
        cars: ["model3-coupe", "model3-hatchback", "model3-cabriolet"]
    }
]

3 个答案:

答案 0 :(得分:1)

for (var i = 0, key; i < modelArray.length; i++) {
    modelArray[i].cars = modelObject[Object.keys(modelObject)[i]];
}

这将循环数组并将属性添加到对象。这假设对象属性都是正确的顺序。

在每次迭代中,它会使用Object.keys()循环使用哪个属性。然后,它将数组中对象的键设置为模型对象的该属性。

答案 1 :(得分:0)

您可以执行类似

的操作

&#13;
&#13;
var models = {

  model1: ["model1-coupe", "model1-hatchback", "model1-cabriolet"],
  model2: ["model2-coupe", "model12-hatchback", "model2-cabriolet"],
  model3: ["model3-coupe", "model4-hatchback", "model4-cabriolet"]

}


var images = [{
  image: "/path/to/image/model1.jpg"
}, {
  image: "/path/to/image/model2.jpg"
}, {
  image: "/path/to/image/model3.jpg"
}]


for (var key in models) {
  if (models.hasOwnProperty(key)) {
    var idx = +key.match(/\d+$/)[0] - 1;
    images[idx][key] = models[key]
  }
}

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

答案 2 :(得分:0)

尝试这样的事情:

var result = [];

var models = {
    // your models object
}
var images = [
    // your images array
];

for(var i=0, key in models) {
    var model = models[key];
    var image = images[i++]; 
    result.push( { image: image, model: model } );
}