0
[
    0: {employeeId: "2", name: "chandan", email: "chandan@gmail.com"}
    1: {gender: "male"}
]

I want this Array like this:

[
  0: {employeeId: "2", name: "chandan", email: "chandan@gmail.com", gender: "male"}
]
Chandan Rathore
  • 73
  • 1
  • 1
  • 7

4 Answers4

2

You can use the spread operator to create a new object, that will copy over the properties of the two existing objects.

arr[0]={...arr[0],...arr[1]};
Mark Colby
  • 191
  • 6
2

array.reduce and spread can help you

const arr = [{
    employeeId: "2",
    name: "chandan",
    email: "chandan@gmail.com"
  },
  {
    gender: "male"
  }
]

const result = arr.reduce((acc, obj) => ({
  ...acc,
  ...obj
}), {});

console.log(result);

--Edit

Object.assign flavor ( seems to be 1% slower on chrome 83 though)

const arr = [{
    employeeId: "2",
    name: "chandan",
    email: "chandan@gmail.com"
  },
  {
    gender: "male"
  }
]

const result = arr.reduce((acc, obj) => Object.assign(acc, obj), {});

console.log(result);
Józef Podlecki
  • 10,453
  • 5
  • 24
  • 50
1

use reduce without initial value will agreggate.

const arr = [
  {
    employeeId: "2",
    name: "chandan",
    email: "chandan@gmail.com",
  },
  {
    gender: "male",
  },
];

const output = arr.reduce((acc, curr) => Object.assign(acc, curr));

console.log(output);
Siva K V
  • 10,561
  • 2
  • 16
  • 29
0

You can also do this by mapping it and then taking fromEntries:

var data=[ {employeeId: "2", name: "chandan", email: "chandan@gmail.com"}, {gender: "male"}];

var result = Object.fromEntries(data.flatMap(k=>Object.entries(k)));

console.log(result);
gorak
  • 5,233
  • 1
  • 7
  • 19