我想创建/读取表的对象(逐列)。我的代码在这里:
var arr1 = [];
var arr2 = [];
for (var i = 0; i < 3; i++) {
var werteArray = [];
var ueberschriftArray = [];
$('#tabelleDateneingabe tbody tr').each(function() {
werteArray.push($(this).children().eq(i).text());
});
$('#tabelleDateneingabe thead tr').each(function() {
ueberschriftArray.push($(this).children().eq(i).text());
});
arr2.push({spalte: i, daten: {ueberschrift: ueberschriftArray, werte:werteArray}});
}
arr1.push(arr2);
运行正常并生成此JSON:
[
[
{
"spalte": 0,
"daten": {
"ueberschrift": [
"Spalte1"
],
"werte": [
"Zelle: 0_0",
"Zelle: 1_0",
"Zelle: 2_0",
"Zelle: 3_0",
]
}
},
{
"spalte": 1,
"daten": {
"ueberschrift": [
"Spalte2"
],
"werte": [
"Zelle: 0_1",
"Zelle: 1_1",
"Zelle: 2_1",
"Zelle: 3_1",
]
}
}]]
现在我想通过这个对象来获取每一行的元素数量。
我很确定这可以通过在“werte”节点上使用length来完成,但是如何为每一列(“spalte”)访问此值?
感谢任何帮助。
答案 0 :(得分:0)
这是一个“替代”的答案,因为这不是规范的做法,但是这种方法非常灵活,你会发现自己希望它总是这么容易......
我建议使用“JSONPath”: http://goessner.net/articles/JsonPath/
允许您查询JSON对象的库,类似于XPath允许您查询XML文档的方式。
然后在您的示例中调用它作为jsonPath(arr1,"..werte.*")
返回匹配项的数组,或jsonPath(arr1,"..werte.*").length
当然返回该数组中的项目数。
答案 1 :(得分:0)
这将返回werte中的一系列条目;
var rowCount = [];
for(var i=0;i<json[0].length;i++) {
var rowArr = json[0][i].daten.werte;
rowCount[i] = rowArr.length;
}
console.log(rowCount);