Reputation: 613
I have 3 regular arrays in javascript
1st array : ids[] (contains list of ids)
2nd array : country[] (contains list of names of countries)
3rd array : codes[] (contains list of codes of countries)
I need to create an object array say 'comb' from these three arrays having keys as "id", "name" and "code" and the respective values from the 3 arrays.
Eg: This is what i want from the regular arrays
var comb = [
{id:1, name:'United States',code:'US'},
{id:2, name:'China',code:'CH'}
];
Can anyone please tell me how to achieve this
Upvotes: 1
Views: 136
Reputation: 3566
I prefer defining objects this way, I think it looks more readable.
function Country(id, country, code) {
this.id = id;
this.country = country;
this.code = code;
}
var comb = new Array();
for(var i = 0; i < ids.length; i++) {
var ctry = new Country(ids[i], country[i], codes[i]);
comb.push(ctry);
}
Upvotes: 3
Reputation: 177786
var comb = [];
for (var i=0,n=ids.length;i<n;i++) {
comb.push({id:ids[i],name:country[i],code:codes[i]});
}
Upvotes: 5