hetennunawi
hetennunawi

Reputation: 73

convert an array of objects to one object of objects

How to convert an array of objects to one object of objects. My function works but I don't want key name before each object.

 myArray = [{
     "name": "ann",
      "y": 191,
      "color": "red"
    },{
     "name": "mary",
      "y": 11,
      "color": "red"
    },{
     "name": "henry",
      "y": 11,
      "color": "red"
    }]

let result = {};
for (let item of seriesTotal) {
  result[item.name] = item;
delete item.name;
}   

I'd like this

myObject = {{
 "name": "ann",
  "y": 191,
  "color": "red"
},{
 "name": "mary",
  "y": 11,
  "color": "red"
},{
 "name": "henry",
  "y": 11,
  "color": "red"
}{

Upvotes: 0

Views: 144

Answers (2)

Emeeus
Emeeus

Reputation: 5250

Since what you want is not valid JS object, you'll get an string in JS, so you could use .replace():

    myArray = JSON.stringify(myArray).replace(/(\[)(.+)(\])/g,"{$2}");

    console.log(myArray);

//{{"name":"ann","y":191,"color":"red"},{"name":"mary","y":11,"color":"red"},{"name":"henry","y":11,"color":"red"}}

But as I said before, that is not a JS object, it's just a string.

Upvotes: 0

Eddie
Eddie

Reputation: 26844

An object is a collection of properties, and a property is an association between a name (or key) and a value.

You can use the index as the key or property name. Use Object.assign to create a new object. Use map and spread syntax to loop thru the array.

let myArray = [{
  "name": "ann",
  "y": 191,
  "color": "red"
}, {
  "name": "mary",
  "y": 11,
  "color": "red"
}, {
  "name": "henry",
  "y": 11,
  "color": "red"
}];


let result = Object.assign(...myArray.map((o,i) => ({[i]: o})));

console.log(result);

Doc: Objects

Upvotes: 1

Related Questions