-2

I am stuck to write a javascript es6 function for converting Array of objects to one object like this

[
    {"uptime": "411694300"}, 
    {"temperature": "54"},
    {"model": "24P"},
    {"version": "5.3.12"},
    {"hostname": "LAB"}
];

to

{
    "uptime": "411694300",
    "temperature": "54",
    "model": "24P",
    "version": "5.3.12",
    "hostname": "LAB"
};
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • [Self-answering](https://stackoverflow.com/help/self-answer) is encouraged but please make sure this question hasn't been asked before. There are plenty of duplicates for this one. – adiga Sep 26 '22 at 09:05

2 Answers2

0

Using Object.assign:

object = Object.assign({}, ...array);

Alternative (using reduce):

object = array.reduce((acc,value)=>({ ...acc, ...value }), {})
Kostas Minaidis
  • 4,681
  • 3
  • 17
  • 25
  • 1
    Very clever solution! But you should also explain how it works. Code-only answers are frowned upon. – CherryDT Sep 26 '22 at 08:42
  • Perhaps also link to some online documentation: [`reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce), [`Object.assign`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign), [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax). – Andy Sep 26 '22 at 08:45
0

You only need to re-insert the object when looping over the array

let x = [
    {"uptime":"411694300"}, 
    {"temperature":"54"},
    {"model":"24P"},
    {"version":"5.3.12"},
    {"hostname":"LAB"}
];
let y = {}

x.forEach(e => {
  let f = Object.entries(e)
  y[f[0][0]] = f[0][1]
})

console.log(y)
adiga
  • 34,372
  • 9
  • 61
  • 83