1

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

1
  • Just FYI, the result you have is an array of objects. Commented Aug 6, 2012 at 7:29

2 Answers 2

5
var comb = [];
for (var i=0,n=ids.length;i<n;i++) {
  comb.push({id:ids[i],name:country[i],code:codes[i]});
}
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.