在Javascript中过滤数组并返回所有相关对象

时间:2015-05-22 20:12:18

标签: javascript arrays object filter

我想用JavaScript过滤一个对象数组。

array(
    (int) 0 => array(
        'DetailedWorkingHour' => array(
            'id' => '326',
            'start' => '07:00:00',
            'end' => '16:00:00',
            'date' => '2015-06-17',
            'working_hour_template_id' => '3'
        ),
        'WorkingHourTemplate' => array(
            'color' => 'red',
            'id' => '3'
        )
    ),
    (int) 1 => array(
        'DetailedWorkingHour' => array(
            'id' => '346',
            'start' => '07:00:00',
            'end' => '16:00:00',
            'date' => '2015-07-01',
            'working_hour_template_id' => '3'
        ),
        'WorkingHourTemplate' => array(
            'color' => 'red',
            'id' => '3'
        )
    )
)

此过滤器函数仅返回DetailedWorkingHour对象,但我需要将两者都作为返回的数组

var filteredResult = filterByProperty(hours, "date", formattedDate);

function filterByProperty(array, prop, value){
    var filtered = [];

    for(var i = 0; i < array.length; i++){
        var obj = array[i];

        for(var key in obj){
            if(typeof(obj[key] == "object")){
                var item = obj[key];

                if(item[prop] == value){
                    filtered.push(item);
                }
            }
        }
    }    
    return filtered;
}

如何在返回的数组中同时拥有这两个对象?

1 个答案:

答案 0 :(得分:1)

obj推送到filtered数组而不是item

function filterByProperty(array, prop, value){
    var filtered = [];

    for(var i = 0; i < array.length; i++){
        var obj = array[i];

        for(var key in obj){
            if(typeof(obj[key] == "object")){
                var item = obj[key];

                if(item[prop] == value){
                    filtered.push(obj);
                    break; // So we only push the object once if multiple matches
                }
            }
        }
    }    
    return filtered;
}