Search code examples
javascriptarraysjavascript-objects

Separate and assign objects to variable from an array


I have the following array that I need to loop through:

var arr = [{
  "id": 111,
  "wbs_name": "Mechanical",
  "parent": 'root',
}, {
  "id": 222,
  "wbs_name": "Electrical",
  "parent": 111,
}, {
  "id": 333,
  "wbs_name": "Systems",
  "parent": 111,
},]

My output should be like this:

 var mechanical = {
     "id": 111,
     "wbs_name": "mechanical",
     "parent": 0,
 },

 var electrical= {
     "id": 222,
     "wbs_name": "electrical",
     "parent": mechanical,
 },

 var systems = {
     "id": 222,
     "wbs_name": "systems",
     "parent": mechanical,
 },

I already tried looping through the array and pushing the object into another, but I don't know how to assign them to a variable at the same time (where the variable name is "wbs_name" and the "parent" is the variable name of some other parent object.


Solution

  • Though polluting the global scope isn't recommended, you can use the following

    arr.forEach( s => { window[s.wbs_name] = s; } )
    

    This code will create a global level variable for each id property of every object in the array.