1

私はこのコードを持っています:

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);

出力は、最後まで各配列に 1 つのオブジェクトが残っていることです。これは望ましくありません。私の計算では、単一のオブジェクト (引用符オブジェクト) が残っている必要があります。

関連する jsFiddle: http://jsfiddle.net/UdzEW/

何か案は?

4

2 に答える 2

3

の考え方は.filter、値がとどまるか行くかを決定するブール値を返す関数を提供することです。配列をその場で変更しないでください。

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)]]「Quotes」オブジェクトで返されます

于 2013-04-11T11:26:15.530 に答える