[英]how to filter on a JavaScript object based on its attributes
I have a JavaScript object 我有一个JavaScript对象
var items = { ids : [
{
label: "red",
complete: true
},
{
label: "green",
complete: false
},
{
label: "blue",
complete: true
}
]
}
I need to filter out based on the complete attribute when I click on the complete button or when I click on all button it show show me all the entries. 当我单击“完成”按钮或单击“所有”按钮时,我需要根据“完整”属性进行过滤,它会显示出所有条目。
How can I do this in the same function 如何在同一功能中执行此操作
I have this function which takes the list DOM element and creates the entries accordingly. 我有此功能,它使用列表DOM元素并相应地创建条目。 I am wondering how could I write this function such that it could filter on the complete status or print all the entries in the redraw function itself. 我想知道如何编写此函数,以便可以对完整状态进行过滤或打印重绘函数本身中的所有条目。
var redraw = function(items) {
list.innerHTML='';
for (var id in items) {
draw(model.todos[id], list);
}
};
var draw = function(Obj, container) {
var el = Template.cloneNode(true);
el.setAttribute('data-id', Obj.id);
container.appendChild(el);
update(Obj);
});
} }
If you're using Underscore , this is pretty simple 如果您使用的是Underscore ,这很简单
var completedItems = {
ids: _.filter(items.ids, function (id) { return id.complete; })
};
Otherwise you could write it by hand 否则你可以手写
var completedItems = {
ids: (function (ids) {
var arr = [];
ids.forEach(function (id) {
if (id.complete) arr.push(id);
});
return arr;
})(items.ids)
};
Add a new function called filterItems
that accepts the items
array and key
and value
parameters and returns a filtered array based on those parameters. 添加一个名为filterItems
的新函数,该函数接受items
数组以及key
和value
参数,并根据这些参数返回过滤后的数组。 Then, just call it from redraw
with the correct arguments. 然后,只需使用正确的参数从redraw
调用它即可。
function filterItems(items, key, value) {
return items.ids.filter(function (el) {
return el[key] === value;
});
}
var redraw = function(items) {
list.innerHTML='';
items = filterItems(items, 'complete', true);
for (var id in items) {
draw(model.todos[id], list);
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.