3

I have two arrays that look like this:

array1 = [1, 2, 3, 4, 5];
array2 = [a, b, c, d, e];

Using JavaScript, I want to convert two arrays of same length into array of objects that would look like this:

newArrayofObjects = [ {key1: 1, key2: a}, {key1: 2, key2: b}, {key1: 3, key2: c},  {key1: 4, key2: d}, {key1: 5, key2: e}] 
3
  • 8
    this seems really straightforward - have you actually tried solving this yourself? i'm sure someone will give you an answer but imo you will do better to spend some time trying to come up with a solution on your own. Commented Feb 19, 2017 at 0:38
  • 1
    hint: get length, iterate using a for loop Commented Feb 19, 2017 at 0:39
  • I've removed the "json" tag from your question because there's no JSON involved here. Commented Feb 19, 2017 at 0:49

2 Answers 2

5

Array.map comes in handy a lot.

var newArray = array1.map(function(e,i){return{key1:e,key2:array2[i]}});
Sign up to request clarification or add additional context in comments.

Comments

3
var array1 = [1, 2, 3, 4, 5], array2 = ['a', 'b', 'c', 'd', 'e'], newArrayofObjects = [];
for(var key = 0; key < array1.length; key++) {
    newArrayofObjects.push({key1 : array1[key], key2 : array2[key]});
}

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.