我想过滤我的JSON响应,这种响应是像这样的数据表行列,有超过100行。现在我想过滤像ModelName上的数据modelName =Buc98
并且还想从每行中删除ModelName列及其各自的值。
{
"cols": [
{
"type": "datetime",
"id": "ModelDate",
"label": "ModelDate"
},
{
"type": "string",
"id": "ModelName",
"label": "ModelName"
},
{
"type": "number",
"id": "value",
"label": "value"
}
],
"rows": [
{
"c": [
{
"v": "Date(2012, 0, 1, 0, 0, 0)"
},
{
"v": "Buc98"
},
{
"v": 100
}
]
}
]
}
答案 0 :(得分:0)
这样的问题的关键是将模型放入更容易使用的表单中。像这样:
{
"cols": [
{
"type": "datetime",
"id": "ModelDate",
"label": "ModelDate"
},
{
"type": "string",
"id": "ModelName",
"label": "ModelName"
},
{
"type": "number",
"id": "value",
"label": "value"
}
],
"rows": [
{
"ModelDate": "Date(2012, 0, 1, 0, 0, 0)",
"ModelName": "Buc98",
"value": 100
}
]
}
所以我们会这样做:o)
var data = {
"cols": [
{
"type": "datetime",
"id": "ModelDate",
"label": "ModelDate"
},
{
"type": "string",
"id": "ModelName",
"label": "ModelName"
},
{
"type": "number",
"id": "value",
"label": "value"
}
],
"rows": [
{
"c": [
{
"v": "Date(2012, 0, 1, 0, 0, 0)"
},
{
"v": "Buc98"
},
{
"v": 100
}
]
}
]
}
//first get a list of the column id's
var colCount = data.cols.length;
var columnIds = [];
for (var i = 0; i < colCount; i++){
columnIds.push(data.cols[i].id);
}
// columnIds = ["ModelDate", "ModelName", "value"];
var rows = [];
var rowCount = data.rows.length;
for (var i = 0; i < rowCount; i++){
var row = {}
for (var j = 0; j< colCount; j++){
var colId = columnIds[j];
row[colId] = data.rows[i].c[j].v;
}
rows.push(row);
}
model.rows = rows;
Phew,行现在采用我们可以使用的格式。
[
{
"ModelDate": "Date(2012, 0, 1, 0, 0, 0)",
"ModelName": "Buc98",
"value": 100
}
]
现在我们有一个合理的结构。我们实际上可以做过滤。为此,我个人定义了一个函数,它返回模型的过滤版本,以便我们可以轻松地进行过滤。
function filter(model, prop, value){
var filteredRows = [];
var rowCount = model.rows.length;
for (var i = 0; i < rowCount; i++){
if (model.rows[i][prop] == value){
filteredRows.push(model.rows[i]);
}
}
//return a filtered version of the model
return {
cols: model.cols,
rows: filteredRows
};
}
然后,您可以使用此过滤版本来呈现您的表等。
var filtered = filter(data, 'ModelName', 'Buc98');
修改 - 更新了答案,以便删除不匹配的行。并添加了使用示例