Correct approach to get JSON node length in JS?

Viewed 43

I have this simple JSON file that supposed to be one array Paths with 3 arrays (Path1, Path2, Path3) of objects.

{
    "Paths":
    
        {
            "Path1": [{"x":"4","y":"182"},{"x":"220","y":"186"}],
            "Path2": [{"x":"4","y":"222"},{"x":"256","y":"217"}],
            "Path3": [{"x":"6","y":"170"},{"x":"216","y":"183"}]
        }
    
}

Considering an online example that I found I am doing this to get the length of Paths node:

// It's Phaser 3 (JS game framework)
// this.cache.json.get('data') -> returns me the JSON contents
var json = this.cache.json.get('data');
for (var pos in json.Paths) {
    var len = parseInt(json.Paths[pos].length)+1;
    console.log(len);
}

Although it works I would like to know if this is the correct approach because it seems to be too much code only to get a node length.

Thanks!

2 Answers

If you are wanting to get a count of all the points in all paths you could access them using Object.values() and then reduce()

const data ={
    "Paths":
    
        {
            "Path1": [{"x":"4","y":"182"},{"x":"220","y":"186"}],
            "Path2": [{"x":"4","y":"222"},{"x":"256","y":"217"}],
            "Path3": [{"x":"6","y":"170"},{"x":"216","y":"183"}]
        }
    
}

const numPoints = Object.values(data.Paths).reduce((a,c) => (a + c.length), 0)

console.log(numPoints)

Not sure if you are trying to print the length of each path or get total length of all paths, if you want to print the length of each path then you can use map

let lengths = Object.values(json.Paths).map(path => path.length + 1)
console.log(lengths)

which will output

[ 3, 3, 3 ]

or forEach like you did

Object.values(json.Paths).forEach(path => console.log(path.length + 1))

if you need the total you can use reduce

let nodeLength = Object.values(json.Paths).reduce((acc, path) => acc + path.length, 0)

which will give you 6

Edit: since in the comment you said you needed to know how many elements are in your object, you can use

Object.keys(json.Paths).length

to get that

Related