αƞjiβ
αƞjiβ

Reputation: 3246

Create single object using two array

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?

Upvotes: 0

Views: 82

Answers (4)

fafl
fafl

Reputation: 7385

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)

Upvotes: 2

kk.
kk.

Reputation: 3945

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)

Upvotes: 0

Ionică Bizău
Ionică Bizău

Reputation: 113345

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

Upvotes: 0

sbking
sbking

Reputation: 7680

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

Upvotes: 0

Related Questions