我有一个名为active_filters
的数组,其中包含对象。有谁知道我如何能够访问category
属性以便使用如下所示?
我的目标是以下
// For each active filter, use category for:
$("#" + category).find("input:checked").each(function()
{
// Do something
}
// End for
有效过滤器数组
{category: "search-filter-type", id: "data-type", value: "ICAR,SCAR", type: "filtered-out-by-car-type"}
{category: "search-filter-company", id: "data-company", value: "BU", type: "filtered-out-by-company"}
{category: "search-filter-location", id: "data-location", value: "AV-123", type: "filtered-out-by-location"}
答案 0 :(得分:0)
由于您有一组对象,您可以使用$.each()
来迭代它们,请参阅下面的演示。
var json = [{
category: "search-filter-type",
id: "data-type",
value: "ICAR,SCAR",
type: "filtered-out-by-car-type"
}, {
category: "search-filter-company",
id: "data-company",
value: "BU",
type: "filtered-out-by-company"
}, {
category: "search-filter-location",
id: "data-location",
value: "AV-123",
type: "filtered-out-by-location"
}];
$.each(json, function(index, filters) {
console.log(filters.category);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
答案 1 :(得分:0)
实际上,您可以遍历categories
并搜索内部的每个category
并使用$("#" + category)
let categories = [{
category: "search-filter-type",
id: "data-type",
value: "ICAR,SCAR",
type: "filtered-out-by-car-type"
}, {
category: "search-filter-company",
id: "data-company",
value: "BU",
type: "filtered-out-by-company"
}, {
category: "search-filter-location",
id: "data-location",
value: "AV-123",
type: "filtered-out-by-location"
}]
categories.forEach(cat => {
let category = cat.category;
console.log(category);
$("#" + category).find("input:checked").each(function() {
// Do something
})
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
答案 2 :(得分:0)
你可以只使用js作为active_filters,如下所示:
active_filters = [
{category: "search-filter-type", id: "data-type", value: "ICAR,SCAR", type: "filtered-out-by-car-type"},
{category: "search-filter-company", id: "data-company", value: "BU", type: "filtered-out-by-company"},
{category: "search-filter-location", id: "data-location", value: "AV-123", type: "filtered-out-by-location"}
];
for (var i in active_filters) {
if (active_filters.hasOwnProperty(i)) {
var category = active_filters[i];
$("#" + category).find("input:checked").each(function() {
// Do something
}
}
}