0
[
    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"}
]

4 Answers 4

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]};
Sign up to request clarification or add additional context in comments.

3 Comments

Array length is not static So I can't use static [0] the keys is dynamic it would be helpful if you suggest code with dynamic value;
So your array has multiple values ? Not only one?
Józef Podlecki's answer allows for a non-static array length.
2

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

5 Comments

This will do it dynamically, regardless of how many elements are in the array. It loops through the array, spreading the results over and over again.
Now I wonder if Object.assign is good alternative to that. Would have to make some tests on jsperf
Added variant with object.assign
@JózefPodlecki any difference between spread & Object.assign?
1

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.