javascript過濾數組多個條件 - javascript filter array multiple conditions

問題:

I want to simplify an array of objects.我想簡化一組對象。 Let's assume that I have following array:讓我們假設我有以下數組:

var users = [{
    name: 'John',
    email: '[email protected]',
    age: 25,
    address: 'USA'
    },
    {
        name: 'Tom',
        email: '[email protected]',
        age: 35,
        address: 'England'
    },
    {
        name: 'Mark',
        email: '[email protected]',
        age: 28,
        address: 'England'
}];

And filter object:和過濾對象:

var filter = {address: 'England', name: 'Mark'};

For example i need to filter all users by address and name, so i do loop through filter object properties and check it out:例如,我需要按地址和名稱過濾所有用戶,所以我循環過濾器對象屬性並檢查它:

function filterUsers (users, filter) {
    var result = [];
    for (var prop in filter) {
        if (filter.hasOwnProperty(prop)) {

            //at the first iteration prop will be address
            for (var i = 0; i < filter.length; i++) {
                if (users[i][prop] === filter[prop]) {
                    result.push(users[i]);
                }
            }
        }
    }
    return result;
}

So during first iteration when prop - address will be equal 'England' two users will be added to array result (with name Tom and Mark), but on the second iteration when prop name will be equal Mark only the last user should be added to array result, but i end up with two elements in array.因此,在第一次迭代中,當prop - address將等於'England'兩個用戶將被添加到數組結果中(名稱爲 Tom 和 Mark),但在第二次迭代中,當prop name將相等時, Mark只應將最後一個用戶添加到數組結果,但我最終得到數組中的兩個元素。

I have got a little idea as why is it happening but still stuck on it and could not find a good solution to fix it.我對它爲什麼會發生有了一點想法,但仍然堅持下去並且找不到解決它的好方法。 Any help is appreciable.任何幫助都是可觀的。 Thanks.謝謝。


解決方案:

參考: https://stackoom.com/en/question/29Yrj
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章