moaningalways
moaningalways

Reputation: 461

javascript map a new array onto an existing one adding new property

I want to append a new array to an existing array.

var input1 = [ { name: 'one' }, { name: 'two' }, { name: 'three' } ];
var input2 = [ { age: '1' }, { age: '2' }, { age: '3' } ];
result = [ { name: 'one',  age: '1' }, { name: 'two', age: '2' }, { name: 'three', name: 'three' } ];

here is my attempt, but it is not working:

var original = "one,two,three";

var myarray = [{ age: '1' }, { age: '2' }, { age: '3' }];
// this myarray could ALSO be an empty [] array.
myarray += original.split(',').map(s =>  ({name: s}));
console.log(myarray)

Please help to achieve this result. thanks (this is not a duplicate question, cuz we are dealing with possible difference in the length of one of the arrays).

Upvotes: 0

Views: 1999

Answers (3)

user3362334
user3362334

Reputation: 2180

If both arrays have the same length, you can loop trough one of them, and you can use Object.assign() to merge objects. For example:

    var input1 = [ { name: 'one' }, { name: 'two' }, { name: 'three' } ];
    var input2 = [ { age: '1' }, { age: '2' }, { age: '3' } ];

    var x = [];

    for (i in input1) {
        x[i] = Object.assign(input1[i], input2[i])
    }

the variable x will hold the value you desire.

Upvotes: 0

caesay
caesay

Reputation: 17271

If you need to handle the case where the two input arrays are different sizes, you'll have to iterate over the maximum length and output to an array a concatenation of the two input objects. Here's an example of how that could be done:

var input1 = [ { name: 'one' }, { name: 'two' }, { name: 'three' } ];
var input2 = [ { age: '1' }, { age: '2' }, { age: '3' } ];
var output = [];

var maxLength = Math.max(input1.length, input2.length);
for (var i = 0; i < maxLength; i++) { 
   // here we create a new object which is a combination 
   // of the item from both input arrays and add it to output
   output.push(Object.assign({}, input1[i], input2[i]));
}

console.log(output);

The output array would be the length of the longest input array.

Upvotes: 1

Max
Max

Reputation: 1557

If you want to merge the objects at the same indexes in the two arrays and then return a new array you can do something like this:

result = input1.map((obj, index) => ({
  ...obj,
  ...input2[index]
}))

edit with working snippet:

const input1 = [ { name: 'one' }, { name: 'two' }, { name: 'three' } ];
const input2 = [ { age: '1' }, { age: '2' }, { age: '3' } ];

function mergeObjectsInArray(arr1, arr2) {
    return arr1.map((obj, index) => ({
      ...obj,
      ...arr2[index]
    }));
}

console.log(mergeObjectsInArray(input1, input2))

Upvotes: 0

Related Questions