-4

Given these two arrays,

arrName = ['john','marry','sean'];
age = [20,19,31];

How can I combine them into an array of objects like this:

[
    {
        "name": "John",
        "age": 20
    },
    {
        "name": "marry",
        "age": 19
    },
    {
        "name": "sean",
        "age": 31
    }
]
royhowie
  • 11,075
  • 14
  • 50
  • 67
aviate wong
  • 745
  • 2
  • 6
  • 10
  • possible duplicate of [merge two arrays of keys and values to an object using underscore](http://stackoverflow.com/questions/12199051/merge-two-arrays-of-keys-and-values-to-an-object-using-underscore) – Dwight Gunning Apr 18 '15 at 07:41
  • @dwightgunning This isn't a dupe, this question has nothing to do with underscorejs – A. Wolff Apr 18 '15 at 07:42
  • @dwightgunning that question specifically asks for a solution that is **not** plain JavaScript – royhowie Apr 18 '15 at 07:42
  • Ok, try this one: http://stackoverflow.com/questions/6921962/merge-two-arrays-keys-and-values-into-an-object -- sorry I picked the wrong question. This question _has_ been asked before. – Dwight Gunning Apr 18 '15 at 07:43
  • @dwightgunning also not the same. That one uses one array as the keys and the other as the values. – royhowie Apr 18 '15 at 07:44
  • If my answer below fully answered your question, consider accepting it. It's a form of closure (and considered good SO etiquette), so that others know that your problem has been solved. (People are also less likely to answer your questions in the future, if they notice that you never accept answers.) In addition, I noticed that you haven't accepted an answer on a lot of your other questions. I implore you to accept the best answer on those posts. – royhowie Apr 19 '15 at 08:25

1 Answers1

2

This is as simple as looping through the arrays, creating an object, and pushing it to a new array. (I suppose you could also do it in place.)

var ageArray = [69, 95, 57],
    nameArray = ["eltonjohn", "Raymond Smullyan", "ellen"],
    myObjects = [];

for (var i = 0; i < ageArray.length; i++) {
    myObjects.push({
        name: nameArray[i],
        age: ageArray[i]
    });
}
console.log(myObjects);

You can access an object with array[index]. You can access an object's properties with array[index].property, e.g., myObjects[2].name is "ellen".

A. Wolff
  • 74,033
  • 9
  • 94
  • 155
royhowie
  • 11,075
  • 14
  • 50
  • 67
  • Ok but you have edited question removing the part asking for JSON object notation – A. Wolff Apr 18 '15 at 07:41
  • @A.Wolff I'm pretty sure the OP is confusing JSON with regular javascript objects. If OP wants a JSON string, he can use `JSON.stringify(myObjects)`. – royhowie Apr 18 '15 at 07:42