How to transform array of objects into object of objects

I have seen lots of answers in the other way, but i couldnt find array of objects into object of objects

the following example of what I want: i want to transform this:

var = [
{"a" : {"min" : 0.5}},
{"b" : {"max" : 0.6}},
{"c" : {"min" : 0.3}}]

to this:

var = {
"a" : {"min" : 0.5},
"b" : {"max" : 0.6},
"c" : {"min" : 0.3}
}

array of objets to object of objects,

So I can use this solver: https://github.com/JWally/jsLPSolver

thanks

Upvotes: 1

Views: 114

Answers (4)

Nenad Vracar
Nenad Vracar

Reputation: 122027

You can do this using Object.assign() and ES6 spread syntax.

var arr = [{"a" : {"min" : 0.5}}, {"b" : {"max" : 0.6}}, {"c" : {"min" : 0.3}}]

var result = Object.assign({}, ...arr);
console.log(result)

Upvotes: 2

philipp
philipp

Reputation: 16485

const obj = arr.reduce((result, item) => {
  const key = Object.keys(item)[0];
  result[key] = item[key];
  return result; 
}, {});

Array.prototype.reduce() and Object.keys() are your friends in here.

I think it is kind of difficult to generalize this and make it more generic, since you have to know which key of the item should be used as key of the result. But in this case, there is only one, so easy to use.

Upvotes: 1

brk
brk

Reputation: 50291

You can do like this. First loop over the array and just add the key & value from each object to the new object

var firstArray = [{
    "a": {
      "min": 0.5
    }
  },
  {
    "b": {
      "max": 0.6
    }
  },
  {
    "c": {
      "min": 0.3
    }
  }
]

var arrayKey = {};
firstArray.forEach(function(item) {
  for (var keys in item) {
    arrayKey[keys] = item[keys]
  }


})
console.log(arrayKey)

Upvotes: 0

pajczur
pajczur

Reputation: 245

I suppose you should create class or struct of objects.

Upvotes: 0

Related Questions