1

I have this code:

var app = {
    items: [
        [{
            title: 'Overview',
            id: 'dashboard'
        }, {
            title: 'Reports',
            id: 'reports'
        }],
        [{
            title: 'Customers',
            id: 'customers'
        }, {
            title: 'Quotes',
            id: 'quotes'
        }, {
            title: 'Sales',
            id: 'sales'
        }],
        [{
            title: 'Suppliers',
            id: 'suppliers'
        }, {
            title: 'Purchases',
            id: 'purchases'
        }],
        [{
            title: 'Bank',
            id: 'bank'
        }, {
            title: 'Projects',
            id: 'projects',
            disabled: true
        }, {
            title: 'Journal',
            id: 'journal',
            disabled: true
        }]
    ]
}

var userDetails = {
    IsAdmin: true
};

for (var x = 0; x < app.items.length; x++) {
    app.items[x].filter(function (items) {
        if (items.disabled || (userDetails.IsAdmin && items.id !== 'quotes')) {
            var ind = app.items[x].indexOf(items);
            app.items[x].splice(ind, 1);
        }
    });
}

console.log(app.items);

The output is that there is 1 object left in each array by the end. This is not desired, by my calculations, there should just be a single object left (the quotes object),

related jsFiddle: http://jsfiddle.net/UdzEW/

Any ideas?

4

2 回答 2

3

的想法.filter是您提供一个函数 tahat 返回一个布尔值,该值确定该值应该保留还是保留;它不应该就地修改数组。

var filtered = app.items[x].filter(function (items) {
    if (items.disabled || (userDetails.IsAdmin && items.id !== 'quotes')) {
        return false;
    }
    return true;
});

的内容filtered现在应该包含一个新数组,其中仅包含那些不符合内部条件的项目。

于 2013-04-11T11:17:53.803 回答
0

尝试这个:

 for (var x = 0; x < app.items.length; x++) {
    app.items[x] = app.items[x].filter(function (items) {
       return !(items.disabled || (userDetails.IsAdmin && items.id !== 'quotes'));
   });
   !app.items[x].length && app.items.splice(x--, 1);
 }

[[Array(1)]]与“报价”对象一起返回

于 2013-04-11T11:26:15.530 回答