-1

I have a json object and a dummy json response. I need to loop through it and get a new array of each coordinates, one per loop.

Sample JSON:

customersBarChart: {
    "2014": {
             "x": 1,
             "y": 5,
             "z":10           
            },
    "2015": {
             "x": 8,
             "y": 2,
             "z":5
            },
}

The expected result is:

first X loop  MyArray = [1,8]
second Y loop MyArray = [5,2]
third Z loop  MyArray = [10,5]
Nic3500
  • 8,144
  • 10
  • 29
  • 40

2 Answers2

0

You can loop over objects using for (let o in obj) and get the values from there. You can now make 3 separate arrays by pushing the data from obj[o] onto the end of the specified array.

let obj = {
  "2014": {
    "x": 1,
    "y": 5,
    "z": 10

  },
  "2015": {
    "x": 8,
    "y": 2,
    "z": 5
  },
}

let arr1 = []
let arr2 = []
let arr3 = []

for (let o in obj) {
  arr1.push(obj[o].x)
  arr2.push(obj[o].y)
  arr3.push(obj[o].z)
}

console.log(arr1.join())
console.log(arr2.join())
console.log(arr3.join())
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
0

here is how to handle things dynamically.

var oData = {
  customersBarChart: {
    "2014": {
      "x": 1,
      "y": 5,
      "z": 10

    },
    "2015": {
      "x": 8,
      "y": 2,
      "z": 5
    },
  }
}

function extractData(data) {
  // get the keys of the customersBarChart object
  var keys = Object.getOwnPropertyNames(data);

  // get the keys of the object in the first item in customersBarChart object
  // and initialize an array
  var attrs = Object.getOwnPropertyNames(data[keys[0]]).map(function(k) {
    return {
      key: k,
      arr: []
    };
  });

  // looping thru the attrs to collect the val for the array
  attrs.forEach(function(attr) {
    keys.forEach(function(k) {
      attr.arr.push(data[k][attr.key]);
    });
  });

  // drop the key property in attrs object
  return attrs.map(function(attr) {
    return attr.arr;
  });
}

console.log(extractData(oData.customersBarChart));
D. Seah
  • 4,472
  • 1
  • 12
  • 20