0

I have two arrays of same length

ids = [123, 456, 789, ...., 999];
names = ['foo', 'bar', ... , 'zzz'];

I want to create an array like

[ {id: 123, name: 'foo'}, {id: 123, name: 'bar'}, ..., {id: 999, name: 'zzz'} ]

I am trying to avoid forEach if possible.

Any suggestions?

4 Answers 4

2

Is map okay?

ids = [123, 456, 789, 999];
names = ['foo', 'bar', 'baz', 'zzz'];

result = ids.map(function(_, i) {
    return {id: ids[i], name: names[i]}
});

console.log(result)

Sign up to request clarification or add additional context in comments.

1 Comment

This was gonna be more or less my answer as well. Just wanted to add a disclaimer for the OP to be weary that with two independent arrays, there is a likelihood that one array could be unequal in length to the other, in which you may end up not creating every pair as a literal, or worse, the ids array has more elements than names, which will cause an error of the index being out of bounds.
0

If you don't want to use any higher-order functions, then just do this:

var objects = [];
for (var i = 0; i < ids.length; i++) {
  objects.push({id: ids[i], name: names[i]});
}

Comments

0

No need for forEach here. Use map which is similar to forEach.

var ids = [123, 456, 999];
var names = ['foo', 'bar', 'zzz'];

var result = ids.map(function (currentId, index) {
  return {
    id: currentId,
    name: names[index]
  };
});

console.log(result);

The forEach version would look like this (notice how similar they are):

var ids = [123, 456, 999];
var names = ['foo', 'bar', 'zzz'];

var result = [];
ids.forEach(function(currentId, index) {
  result.push({
    id: currentId,
    name: names[index]
  });
});

console.log(result);

Comments

0

The below code uses foreach but you dont need to handle it. I hope this will work for you.

    ids = [123, 456, 789, 999];
    names = ['foo', 'bar', 'zab', 'zzz'];
    
    result = ids.map(function(_, i) {
        return {id: ids[i], name: names[i]}
    });
    
    console.log(result)

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.