-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"
};
1
  • Self-answering is encouraged but please make sure this question hasn't been asked before. There are plenty of duplicates for this one. Commented Sep 26, 2022 at 9:05

2 Answers 2

0

Using Object.assign:

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

Alternative (using reduce):

object = array.reduce((acc,value)=>({ ...acc, ...value }), {})
Sign up to request clarification or add additional context in comments.

2 Comments

Very clever solution! But you should also explain how it works. Code-only answers are frowned upon.
Perhaps also link to some online documentation: reduce, Object.assign, spread syntax.
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)

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.