javascript - 在JS中获取JSON节点长度的正确方法?

标签 javascript arrays json

我有一个简单的 JSON 文件,它应该是一个包含 3 个对象数组(Path1、Path2、Path3)的数组 Paths

{
    "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"}]
        }
    
}

考虑到我发现的一个在线示例,我这样做是为了获取路径节点的长度:

// 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);
}

虽然它有效,但我想知道这是否是正确的方法,因为它似乎只是为了获取节点长度而需要太多代码。

谢谢!

最佳答案

如果您想获取所有路径中所有点的计数,您可以使用 Object.values() 然后使用 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)

关于javascript - 在JS中获取JSON节点长度的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67649962/

相关文章:

javascript - 如何在 HighChart 中用多个 yAxis 填充两个系列之间的区域?

c# - 使用各种方法将访问者重定向到网站的不同区域?

arrays - 同时遍历两个数组

java - 将频率应用于数组中的元素

mysql - JQGrid 与 ASP.net 和 MySQL 不显示记录

javascript - 您如何称呼 Oracle 使用的顶部导航菜单?

javascript - 计算样式组件的高度

python - (x,) 在 NumPy 形状中表示什么?

javascript - 如何将 .geojson 文件转换为带有嵌套数组的 JavaScript 对象?

c++,使用nlohmann::json解析JSON数组