1

This is a follow up to again Push same multiple objects into multiple arrays.

AFter I create my objects:

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

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

And push values using @NickParsons solution:

$.getJSON(json, result => {
  result.forEach(elem => {
   objects.forEach(obj => {
     obj.arr.push({
       x: elem.date,
       y: elem.val2
     });
   });
  });
 });

Here I am adding my objects, i.e. x and y based on no condition. But I want to add it based on if indexOf(obj.xyz) = elem.val1.

THis is my JSON:

  [
{
    "date": "2019-07-21",
    "val1": "xyz1_hello",
    "val2": 803310
},
{
    "date": "2019-07-22",
    "val1": "xyz2_yellow",
    "val2": 23418
},
{
    "date": "2019-07-22",
    "val1": "xyz1_hello",
    "val2": 6630
},
{
    "date": "2019-07-24",
    "val1": "xyz2_yellow",
    "val2": 4
},
{
    "date": "2019-07-21",
    "val1": "xyz3_yo",
    "val2": 60984
}
]

Is there a way for me to push values to x and y if obj.xyz is LIKE (indexOF) elem.val1 For example, if indexOf(obj.xyz) = elem.val1, then push their corresponding elem.date and elem.val2 data to obj.arr.

Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
nb_nb_nb
  • 1,243
  • 11
  • 36

1 Answers1

1

Assuming you have some boolean like(a,b) function that decides if two values are similar or not, and your elements are in elems:

objects.forEach(o => 
  elems.forEach(e => {
    if(like(o.xyz, e.val1)){
      o.arr.push({
        x: e.date,
        y: e.val2
      });
    }
  }));
David Sampson
  • 727
  • 3
  • 15