我有以下json数组:
{"0":
{"ChkSystem":
{"id":"847",
"item":"1",
"fase":"#FE99CC",
"description":"some info.",
"image_path":"",
"pm_id":"461",
"main_systems_id":"1"
}
},
"1":
{"ChkSystem":
{"id":"846",
"item":"1",
"fase":"#FE99CC",
"description":"some data",
"image_path":"",
"pm_id":"461",
"main_systems_id":"2"
}
},
"2":
{"ChkSystem":
{"id":"856",
"item":"2",
"fase":"#FE99CC",
"description":"some data.",
"image_path":"",
"pm_id":"461",
"main_systems_id":"2"
}
}
}
如何使用jquery按"main_systems_id"
过滤它?
问题是密钥是变量("0"
,"1"
等等),而在我读过的其他帖子中,密钥总是相同的。
提前感谢您的回答。
答案 0 :(得分:1)
我认为像lodash或underscore这样的工具更适合这种性质。
但是你真的想用jQuery做这件事:
function filterByMainSystemsId (object, value) {
// The real meat of the solution, you can use this directly if you want.
return $.map(object, function (item, key) {
// this is where the check is done
if (item.ChkSystem.main_systems_id === value) {
// if you want the index or property "0", "1", "2"... etc.
// item._index = key;
return item;
}
});
};
}
var object = /* ... your object goes here ... */;
var array = filterByMainSystemsId(object, "2") // [ { ... }, { ... } ]
我同意,这应该是一个数组,而不是一个对象,但像弹性搜索和其他工具这样的东西使这很难,我可以理解。
答案 1 :(得分:0)
这不是数组,而是包含子对象的对象。这将是json数组的代码:
[
{"ChkSystem":
{"id":"847",
"item":"1",
"fase":"#FE99CC",
"description":"some info.",
"image_path":"",
"pm_id":"461",
"main_systems_id":"1"
}
},
{"ChkSystem":
{"id":"846",
"item":"1",
"fase":"#FE99CC",
"description":"some data",
"image_path":"",
"pm_id":"461",
"main_systems_id":"2"
}
},
{"ChkSystem":
{"id":"856",
"item":"2",
"fase":"#FE99CC",
"description":"some data.",
"image_path":"",
"pm_id":"461",
"main_systems_id":"2"
}
}
]
但您也可以遍历json对象(键值对)并进一步过滤它们。见StackOverflow: loop and get key/value pair for JSON array using jQuery