Home > Enterprise >  how to convert multi element object to one element object
how to convert multi element object to one element object

Time:03-17

I have object like this

[
  { A: '1' },
  { B: '2' },
  { C: '3' },
]

I want convert to like this

{
  A: '1',
  B: '2',
  C: '3',
}

what is the best way to do it

CodePudding user response:

  • Object.assign with spread syntax
let arr = [
  { A: '1' },
  { B: '2' },
  { C: '3' },
]

console.log(Object.assign(...arr));

CodePudding user response:

let arr = [
  { A: '1' },
  { B: '2' },
  { C: '3' },
]

let output = {}

arr.map((obj) => {
    output = {...output, ...obj}
})

console.log(output)

CodePudding user response:

Object.assign and spread operator will do the trick :

let arrObject = [
   { A: "1" }, 
   { B: "2" },
   { C: "3" }
]; 
  1. Object.assign(target, ...sources)

let obj = Object.assign({}, ...arrObject);

console.log(obj) => obj = { A: '1', B: '2', C: '3' }

  • Related