0

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

moaningalways
  • 461
  • 1
  • 10
  • 21
  • You can’t just _add_ two arrays and expect their object properties to be merged. – Sebastian Simon Nov 21 '17 at 02:24
  • @Xufox supposing that they have the same number of elements. – moaningalways Nov 21 '17 at 02:25
  • Hint: Loop over one...use index to modify the other at same position – charlietfl Nov 21 '17 at 02:26
  • What’s the expected outcome if `myarray` is empty or has fewer elements than `original.split(",")`? – Sebastian Simon Nov 21 '17 at 02:26
  • @moaningalways If you just want to merge the elements of both arrays, you could use something like `input1.map((element, index) => Object.assign({}, element, input2[index]))` – grovesNL Nov 21 '17 at 02:28
  • @Xufox normally they should have the same length, if not, then i return an error. Actually at first, it is empty, i assign an array to it, and then i merge it with the upcoming ones. so at first it is empty, and later it should be the same length and be merged. – moaningalways Nov 21 '17 at 02:29
  • 2
    Possible duplicate of [How do I zip two arrays in JavaScript?](https://stackoverflow.com/questions/22015684/how-do-i-zip-two-arrays-in-javascript) – qxg Nov 21 '17 at 02:55

3 Answers3

1

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.

caesay
  • 16,932
  • 15
  • 95
  • 160
  • Overcomplicating this iff OP starts with a string – charlietfl Nov 21 '17 at 02:28
  • 2
    @charlietfl are you just trolling? If you're not I'd appreciate an explanation or the very least an alternative answer which can handle the case where the input arrays are different lengths demonstrating how this is overcomplicated. – caesay Nov 21 '17 at 02:33
0

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))
Max
  • 1,517
  • 9
  • 16
  • Note that the object spread syntax isn’t official ES syntax yet. It’s a stage 3 proposal of the next ES edition. – Sebastian Simon Nov 21 '17 at 02:33
  • This is fine if you are using a compiler like TS, Babel, etc - but if you're using native javascript you should be using `Object.assign()` like in my answer below. Also, this doesn't handle the case where the arrays are different lengths like mine either. – caesay Nov 21 '17 at 02:37
  • The question was tagged ES-6, however I agree that `Object.assign` should be used if you are not using a transpiler. – Max Nov 21 '17 at 02:57
0

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.

user3362334
  • 1,980
  • 3
  • 26
  • 58
  • Why the downvote? What is wrong with this answer? This code works, and I explained what the idea behind this solution. – user3362334 Nov 21 '17 at 18:15
  • I could also ask why my answer is +4/-4 right now and is the accepted answer. This question is super toxic for some reason. There's also a few deleted answers at -3 and -4 – caesay Nov 22 '17 at 04:49