3

Sorry... I made a misstake about example...

I want to convert Object Array to Single Object.

Before

[
 {key: "A", value: "a"},
 {key: "B", value: "b"},
 {key: "C", value: "c"},
 .
 .
 .
]

After

{
 A: "a",
 B: "b",
 C: "c"
 .
 .
 .
}

I try to use Object.assign(), but it doesn't work well.

Do you know any good methods for that?

Pirikara
  • 343
  • 3
  • 12
  • 1
    @NickParsons: strangely, this dupe wasn't closed by another golden badge owner who was the author of (exactly the same) accepted answer in that thread – Yevhen Horbunkov Sep 17 '20 at 11:25
  • @YevgenGorbunkov oh lol, didn't even realize. I guess the question/answer is 3 years old so they may have forgotten about their old answer... – Nick Parsons Sep 17 '20 at 11:26
  • 1
    @Jamm : you seem to be switching directions too fast, though, the latest edit of my answer returns your expected output. – Yevhen Horbunkov Sep 17 '20 at 12:09

4 Answers4

4

You may use Array.prototype.reduce():

const src = [{key:"A",value:"a"},{key:"B",value:"b"},{key:"C",value:"c"}],

     result = src.reduce((acc, {key,value}) => 
      (acc[key] = value, acc), {})
      
console.log(result)
Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42
0

You coulds spread ... the objects with Object.assign.

const 
    data = [{ name: 'A' }, { firstname: 'Jamm' }, { age: "23" }],
    object = Object.assign({}, ...data);

console.log(object);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can use reduce and inside callback iterate the object to add keys and value to the accumulator object

let data = [{
    name: 'A'
  },
  {
    firstname: 'Jamm'
  },
  {
    age: "23"
  },
]
const newData = data.reduce((acc, curr) => {

  for (let keys in curr) {
    acc[keys] = curr[keys]

  }

  return acc;
}, {});

console.log(newData)
brk
  • 48,835
  • 10
  • 56
  • 78
0

You can use the Array.prototype.reduce to combine the individual objects into one single object:

const data = [{ name: 'A' }, { firstname: 'Jamm' }, { age: '23'}];

function combineObjects(arr) {
  return arr.reduce((acc, o) => {
    return { ...o,  ...acc };
  }, {});
}
console.log(combineObjects(data));
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44