0

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"
}{
2
  • 7
    what you want is not a valid js object. Commented Jun 15, 2018 at 15:51
  • 1
    As mentioned, that is not a valid object, so instead tell how you want to use it by providing us with a working code sample Commented Jun 15, 2018 at 15:57

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.