[英]What is the best way to delete object from complex JavaScript object
I have a JavaScript object which looks like this: 我有一个JavaScript对象,看起来像这样:
{
"filters": [
{
"name": "Test",
"items": [
{
"id": 1207700620,
"checked": false
},
{
"id": 1207825584,
"checked": false
},
{
"id": 1207969166,
"checked": true
}
]
},
{
"name": "Empty",
"items": []
},
{
"name": "ThirdList",
"items": [
{
"id": "1207828314",
"checked": true
},
{
"id": "1236723086",
"checked": false
},
{
"id": "1208005603",
"checked": true
}
]
}
]
}
My object
have a array by the name filters
. 我的object
有一个名为filters
的数组。 This array contains multiple objects. 该数组包含多个对象。 Within each object there is an array by name items
. 在每个对象中,都有一个由名称items
的数组。 For each element in this items
array, I need to check the checked
property & if it is false, I need to delete that record (that item in items array)
. 对于此items
数组中的每个元素,我需要检查checked
属性, if it is false, I need to delete that record (that item in items array)
。
I need to ensure IE 8 compatability . 我需要确保IE 8的兼容性 。
I can use a for loop on filters array and within this for loop I can use another for loop to go over items array. 我可以在过滤器数组上使用for循环,并且在此for循环中可以使用另一个for循环遍历items数组。 I dont want this apporach. 我不要这个办法。
Is there smarter way to achieve this by lodash or jquery or any other JavaScript library?? 有没有更聪明的方法可以通过lodash或jquery或任何其他JavaScript库实现这一目标?
You can try a combination of forEach
and filter
methods: 您可以尝试使用forEach
和filter
方法的组合:
obj.filters.forEach(function(filter) {
filter.items = filter.items.filter(function(el) {
return el.checked;
});
});
Check example below. 检查下面的例子。
var obj = { "filters": [ { "name": "Test", "items": [ { "id": 1207700620, "checked": false }, { "id": 1207825584, "checked": false }, { "id": 1207969166, "checked": true } ] }, { "name": "Empty", "items": [] }, { "name": "ThirdList", "items": [ { "id": "1207828314", "checked": true }, { "id": "1236723086", "checked": false }, { "id": "1208005603", "checked": true } ] } ] }; obj.filters.forEach(function(filter) { filter.items = filter.items.filter(function(el) { return el.checked; }); }); alert( JSON.stringify(obj, null, 4) );
For IE8 compatibility you can use polyfills or ES5 shims. 为了实现IE8兼容性,可以使用polyfills或ES5垫片。
Another option if you can use Underscore/Lo-Dash, you can go with analog methods: _.each
and _.filter
instead of Array.prototype.forEach
and Array.prototype.filter
: 如果可以使用Underscore / Lo-Dash,则可以使用模拟方法: _.each
和_.filter
而不是Array.prototype.forEach
和Array.prototype.filter
:
_.each(obj.filters, function(filter) {
filter.items = _.filter(filter.items, function(el) {
return el.checked;
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.