2

I have two arrays with an equal amount of objects in them. I want to take each array's first object and put them together in a new array as the first object in the array. I then would like to keep doing that with the following objects.

var a = [{akey: 'something'}, {bkey: 'somethingelse'}];
var b = [{ckey: 'somethinghere'}, {dkey: 'somethingdiffrent'}];

//some-code-here to make the below part.

var newArray  = [{akey: 'something', ckey: 'somethinghere'},
                 {bkey: 'somethingelse', dkey: 'somethingdiffrent'}];

So that I still have the data from the objects in the old arrays but put together as two new objects in one new array. Except duplicate keys, then they can be overwritten, like so:

{aKey: 'data'} + {aKey: 'data'} whould just be {aKey: 'data'}

Hope this makes some sense, the arrays will be the same length, a.length = b.length, but the objects might be different in sense. The final array will be put out on an ng-repeat, (angular project).

G5W
  • 36,531
  • 10
  • 47
  • 80
M.Wendel
  • 33
  • 6

1 Answers1

1

You could use Object.assign to combine the objects and use Array#map for mapping the array.

var a = [{akey: 'something'}, {bkey: 'somethingelse'}, { foo: 'from a' }],
    b = [{ckey: 'somethinghere'}, {dkey: 'somethingdiffrent'}, { foo: 'from b' }],
    c = a.map(function (el, i) {
        return Object.assign({}, el, b[i]);
    });

console.log(c);
.as-console-wrapper { max-height: 100% !important; top: 0; }

If you like to get { foo: 'from a' }, you can switch el and b[i].

return Object.assign({}, b[i], el);

var a = [{akey: 'something'}, {bkey: 'somethingelse'}, { foo: 'from a' }],
    b = [{ckey: 'somethinghere'}, {dkey: 'somethingdiffrent'}, { foo: 'from b' }],
    c = a.map(function (el, i) {
        return Object.assign({}, b[i], el);
    });

console.log(c);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • This solved my problem! – M.Wendel Jan 26 '17 at 14:57
  • 1
    Yes im sorry, i unfortunately missclicked on the wrong button and now i cant seem to find where to redo it. I voted on yours but since i have less then 15 points i cant get it to show yet, and thats why i commented on your answer instead to at least let you know im greatful. – M.Wendel Jan 26 '17 at 15:21