Home > Software design >  Merge a second object array with my array by index regardless of lengths
Merge a second object array with my array by index regardless of lengths

Time:11-08

I have two array of objects with no common properties:

let a = [
  {id: 1}, 
  {id: 2},
  {id: 3},
];

let b = [
  {day: 12},
  {day: 15}
];

I want to merge the props of b into a. Initially, I tried

let m = a.map((i,x) => ({id: i.id, day: b[x].day}));

This worked just fine as long as the lengths of both the arrays were the same. But when b was shorter or a was shorter, that would result in an error

Uncaught TypeError: Cannot read properties of undefined (reading 'day')

I don't really care about the length of b, all I want is a, and if b has an element at the same index, I want that b.day.

I ended up doing this:

let a = [
  {id: 1}, 
  {id: 2},
  {id: 3},
];

let b = [
  {day: 12},
  {day: 15}
];

let m = [];

a.forEach((i, x) => {
  let item = { id: i.id };

  if (b.length > x) {
    item['day'] = b[x].day;
  }

  m.push(item);
});

console.log(m);

This works fine, but it is decidedly uncool. I know this is probably more readable, but, go with me on this one. Is there a way to make this more ES6 friendly? Is there a shorter / more concise way of achieving this please?

CodePudding user response:

You could map the properties with spreading. If value at index is undefined, it acts like an empty object.

const
    a = [{ id: 1 }, { id: 2 }, { id: 3 }],
    b = [{ day: 12 }, { day: 15 }],
    m = a.map((o, i) => ({ ...o, ...b[i] }));

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

CodePudding user response:

Create a new array with the maximum length of both arrays. Loop through this array and return the objects from both a and b array.

let a = [{ id: 1 }, { id: 2 }, { id: 3 }];

let b = [{ day: 12 }, { day: 15 }];

const dummyArray = new Array(Math.max(a.length, b.length)).fill(0)

let m = dummyArray.map((_, index) => ({...a[index], ...b[index]}));

console.log(m);

CodePudding user response:

If I understood your question correctly. A simple way of merging 2 arrays while also merging the objects at the same index:

  let a = [{ id: 1 }, { id: 2 }, { id: 3 }];

  let b = [{ day: 12 }, { day: 15 }];

  let m = [];

  //merge a and b together in m
  m = a.map((item, index) => (b[index] ? { ...item, ...b[index] } : item));
   
  console.log(m);

//output

m= [
    {
        "id": 1,
        "day": 12
    },
    {
        "id": 2,
        "day": 15
    },
    {
        "id": 3
    }
]
  • Related