我有一个简单的 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/