有没有办法从以下内容中获取长度:
{
"11": {
"id": "456",
"uuid": "b596362a-b5bb-4n94-8fd5-1e9fh6fd877b",
"name": "Test",
"description": "Test"
},
"22": {
"id": "739",
"uuid": "c4ccbddf-5177-482f-b5e8-cdd4f699e6b7",
"name": "Test2",
"description": "Test2"
},
"33": {
"id": "737",
"uuid": "m4ccbddv-5177-482f-b5e8-cdd4f699e6b7",
"name": "Test3",
"description": "Test3"
}
}
长度应该是3。我尝试使用JSON.stringify(data).length
,但这给出了整个字符串的长度。
最佳答案
除了上面的答案之外,显然,现代浏览器还有一个 Object.keys
功能。在这种情况下,您可以这样做:
Object.keys(jsonArray).length;
您可以使用以下功能
function getJsonItemLength(item) {
if (typeof item !== undefined && varNotNull(item) && item) {
if (Array.isArray(item)) {
return item.length;
} else if (typeof item === 'object' ) {
return Object.keys(item).length;
} else if (typeof item === 'string' ) {
return item.length
} else {
return 0;
}
}
return 0;
}
关于javascript - 如何确定对象内包含对象的JSON的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37280425/