Search code examples
javascriptecmascript-5

Loop though a JSON and get arrays based on position


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]

Solution

  • 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())