2

This is a follow up to Make 3 arrays correspond to each other with the first being the object name.

AFter I create my objects:

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

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

I use getJSON and want to use those values to push into the array: arr[]. I have multiple objects that have the arr[] and I want to push values into all of them.

This is what I tried so far:

$.getJSON(json, result => 
    {result.forEach((elem, i, array) => 
       {object1.arr.push({x:elem.val1, y:elem.val2});
       {object2.arr.push({x:elem.val1, y:elem.val2});
       {object3.arr.push({x:elem.val1, y:elem.val2});
    }) 
 }); 

When I do this one by one, it works. No errors. Is there a way for me to push these same values into how many ever object[i] I have?

I tried:

 $.getJSON(json, result => 
    {result.forEach((elem, i, array) => 
       (for let j=0; j<=5; j++) {
           {object[i].arr.push({x:elem.val1, y:elem.val2});
       )       
    }) 
 });

When I do this I get Cannot call method 'push' of undefined.

Is there a way to do this without making my code long and bulky?

nb_nb_nb
  • 1,243
  • 11
  • 36
  • I'm surprised that `object1.data.push` works when `data` isn't defined on `object1` ? – Nick Parsons Aug 20 '19 at 10:53
  • 1
    That was my bad. Let me fix the code. I forgot to fix that when I typed it out here – nb_nb_nb Aug 20 '19 at 10:55
  • Make a jsFiddle to demonstrate the problem. Would make it a thousand times easier to debug than the already buggy js you’re adapting from your real code. – Strelok Aug 20 '19 at 11:00

2 Answers2

2

object[i] refers to an array named object which obviously doesn't exist.

Try this oneliner instead:

$.getJSON(json, result => result.forEach((elem, i, array) => window['object' + (i + 1)].data.push({ x: elem.val1, y: elem.val2 })));
Guerric P
  • 30,447
  • 6
  • 48
  • 86
2

Instead of dynamically creating variables using window, you can use an array to store a collection of your objects like so:

let xyzArr = ["xyz1", "xyz2", "xyz3"];
let theArr = [[], [], []];
let objects = [];

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

And then when adding data to each object, you can loop through it using a .forEach() on your objects array like so:

$.getJSON(json, result => {
  result.forEach(elem => {
    objects.forEach(obj => {
      obj.arr.push({
        x: elem.val1,
        y: elem.val2
      });
    });
  });
});
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64