Search code examples
javascriptnode.jsjsonmultidimensional-arrayjavascript-objects

Converting JSON object into array of arrays in javascript


I have tried to take the particular array value of key from a JSON object and store that in an array which will be look like this.

Example:

var obj = { "1":{"class":2,"percent":0.99,"box":[0.2,0.3,0.4,0.5]},
            "2":{"class":2,"percent":0.99,"box":[0.12,0.23,0.45,0.56]},
            "3":{"class":2,"percent":0.99,"box":[0.52,0.83,0.34,0.59]}
           } 

and so on like this

Now i need to take the value of key "box" and store in an array.

var list = []
list = [[0.2,0.3,0.4,0.5],[0.12,0.23,0.45,0.56],[0.52,0.83,0.34,0.59]]

But, i tried multiple ways to store the array inside the array, but i could able to get like this when i printed the list

list = 0.2,0.3,0.4,0.5,0.12,0.23,0.45,0.56,0.52,0.83,0.34,0.59

Solution

  • You can use Object.keys (which returns an array of all key of your json) in combination with array’s map to transform your json into a new array:

    const boxes = Object.keys(obj).map(key => obj[key].box)
    

    You can also use Object.values, which is actually nicer in your case:

    const boxes = Object.values(obj).map(value => value.box)
    

    How it works

    Object.keys return an array:

    Object.keys(obj) // ["1", "2", "3"]
    

    then you can map over them to get the value of each item:

    Object.keys(obj).map(key => obj[key]) // [{box: [...]}, {box: [...]}, {box: [...]}]
    

    then in array.map's callback, you can simply only return the box value:

    Object.keys(obj).map(key => obj[key].box) // [[...], [...], [...]]
    

    Without Object.keys()

    function getBoxes (object) {
      var boxes = [];
      for (var key in object) {
        if (!object.hasOwnProperty(key)) continue;
        boxes.push(object[key].box);
      }
      return boxes;
    }
    
    console.log(getBoxes(obj))
    

    for...in can loop through object's properties, but it'll also loop over inherited properties, therefore we need to guard the loop with object.hasOwnProperty(key).


    Object.keys(): Return an array of all enumerable property names of an object

    Object.values(): Return an array of all enumerable values of an object

    array.map(): Return a new array with each item of the original array transformed in a given callback function

    array.slice(): Return a shallow copy of the original array