Mauro74
Mauro74

Reputation: 4826

Javascript merge an object and an array

My problem is to merge an object and an array of objects.

Here's my object:

{

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

}

Here's my array of objects:

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

I'd like to merged them like that:

[
    {
        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"]
    }
]

How do I do that? I can use either JavaScript or Underscore.

Thanks in advance

EDIT: see how the merging result would actually be:

[
    {
        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"]
    }
]

Upvotes: 0

Views: 93

Answers (3)

Code Uniquely
Code Uniquely

Reputation: 6373

try something like this:

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

Upvotes: 0

Scimonster
Scimonster

Reputation: 33399

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

This will loop the array and add the property to the object. This assumes that the object properties are all in the proper order.

In each iteration, it loops up which property it's up to using Object.keys(). Then, it sets that key of the object in the array to that property of the model object.

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

You can do something like

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)

Upvotes: 0

Related Questions