fivedoor fivedoor - 2 months ago 8
Javascript Question

create an array of objects from an object and array

I have an object:

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


and an array:

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


I want to merge these with the desired output:

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


I thought I would be able to do it quite simply with a for loop like the following (though any method would do):

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


What I actually get is :

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


I guess it's iterating through all instances of
i
for each
obj
each time but how do I amend to get the desired output?

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

thanks!

Answer

you want a new object for each iteration

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