Chandan Rathore
Chandan Rathore

Reputation: 73

How to merge Array Key value from another Key in JavaScript

[
    0: {employeeId: "2", name: "chandan", email: "[email protected]"}
    1: {gender: "male"}
]

I want this Array like this:

[
  0: {employeeId: "2", name: "chandan", email: "[email protected]", gender: "male"}
]

Upvotes: 0

Views: 47

Answers (4)

Rajneesh
Rajneesh

Reputation: 5308

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

var data=[ {employeeId: "2", name: "chandan", email: "[email protected]"}, {gender: "male"}];

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

console.log(result);

Upvotes: 0

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

use reduce without initial value will agreggate.

const arr = [
  {
    employeeId: "2",
    name: "chandan",
    email: "[email protected]",
  },
  {
    gender: "male",
  },
];

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

console.log(output);

Upvotes: 1

Józef Podlecki
Józef Podlecki

Reputation: 11283

array.reduce and spread can help you

const arr = [{
    employeeId: "2",
    name: "chandan",
    email: "[email protected]"
  },
  {
    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: "[email protected]"
  },
  {
    gender: "male"
  }
]

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

console.log(result);

Upvotes: 2

Mark Colby
Mark Colby

Reputation: 191

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]};

Upvotes: 2

Related Questions