2

I currently have multiple objects that look like:

let object1 = {
     xyz: 'xyz1',
     arr: []
    },
    object2 = {
     xyz: 'xyz2',
     arr: []
    },
    object3 = {
     xyz: 'xyz3',
     arr: []
    }

This is getting very long and redundant. Is there anyway I can create 3 arrays like:

let objName = ["object1", "object2", "object3"]
let xyzArr = ["xyz1", "xyz2","xyz3"]
let theArr = [[], [], [] ]

Is there anyways to correspond them to each other?

nb_nb_nb
  • 1,243
  • 11
  • 36

2 Answers2

2

I'm not sure what you're asking, but this would take the 3 arrays and store the objects in the window:

let objName = ["object1", "object2", "object3"];
let xyzArr = ["xyz1", "xyz2","xyz3"];
let theArr = [[], [], []];

objName.forEach((name, index) => {
  window[name] = {
    xyz: xyzArr[index],
    arr: theArr[index]
  };
});

console.log(object1);
console.log(object2);
console.log(object3);

I would recommend using a namespace instead of making them global (more on that here), but I guess this works?

GammaGames
  • 1,617
  • 1
  • 17
  • 32
  • quick question. I have a `$.getJSON(json, result => {result.forEach((elem, i, array) => {object1.data.push({x:elem.val1, y:elem.val2})}) });` All 3 objects will have the same data is there a way for me not to repeat myself by adding `object2.data.push...` and just using a loop to add it once? – nb_nb_nb Aug 20 '19 at 03:25
  • @noob I would need more example data to understand what you're trying to do, it's a bit much to go off of that. – GammaGames Aug 20 '19 at 03:52
  • I am using it to build a highcharts graph. `xyz1` is a name and 'theArr` the x and y data – nb_nb_nb Aug 20 '19 at 03:57
1

There's no automatic way to obtain the objName array from your objects, however you can create an intermediate array which stores [object1,object2,object3] and then use Array#map() to obtain the attribute arrays of xyzArr and theArr as shown below:

let object1 = {
    xyz: 'xyz1',
    arr: []
  },
  object2 = {
    xyz: 'xyz2',
    arr: []
  },
  object3 = {
    xyz: 'xyz3',
    arr: []
  }
  
/* Intermediate step */
const array = [object1, object2, object3];

/* Map each item of array to obtain attribute arrays */
let xyzArr = array.map(item => item.xyz);
let theArr = array.map(item => item.arr);

console.log('xyz',xyzArr);
console.log('arr',theArr);
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
  • Thank you for responding. Bit I dont want to do the `let object1 = {xyz: 'xyz1',arr: []}...` But I want my 3 array's to correspond to that – nb_nb_nb Aug 19 '19 at 22:18
  • So you want to initalise the arrays in your source code directly, based on those objects, rather than to do this programatically ? – Dacre Denny Aug 19 '19 at 22:24
  • I want the `object1` from the first array to be my objectName, `xyz:xyz1` to be my first key value pair and `arr:[]` my next one. – nb_nb_nb Aug 19 '19 at 22:26