JS - 通过属性值数组过滤对象数组并返回过滤对象的数组

时间:2017-09-06 22:54:26

标签: arrays filter find javascript-objects

我正在尝试(在js或jquery中)过滤对象数组并返回具有特定属性名称的对象数组。

我尝试了filterfind这样的功能:

var objs = [{ a:1, }, {a:2}, {a:3}, {a:4}]
var vals = [1, 2]

  function callback(obj) {
        var arr = arr || []
        console.log(arr)
        $.each(vals, function(key, val) {
            if ( val == obj.a ) {
                arr.push(obj)
            }
        })
    }

    var result = objs.find(callback);

    console.log(">>>", result)

预期结果是:

result = [{a:1}, {a:2}]

然而它不起作用,因为find的每次迭代重新开始,并重新定义arr

我当然可以使用两个嵌套的$.each() - 一个迭代对象数组,第二个遍历属性值数组但我认为是最后一个选项 - 寻找更优雅,更短的东西。你们有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您可以使用filterindexOf

进行此操作

var objs = [{ a:1, }, {a:2}, {a:3}, {a:4}]
var vals = [1, 2]


function filterByValue(source, allowedValues) {
  // Return the result of the filter.
  return source.filter(item => {
    // Returns true when `a` is present in vals (index > -1); otherwise it returns false.
    return allowedValues.indexOf(item.a) > -1;
  });
}

const
  filteredArray = filterByValue(objs, vals);

console.log(filteredArray)

答案 1 :(得分:0)

Thijs的回答是有效的,但随着vals数组变大,它将无法实现。要获得O(n)复杂性,您可以构建allowedValues数组的集合:



var objs = [{ a:1, }, {a:2}, {a:3}, {a:4}]
var vals = [1, 2]

function filterByValue(source, allowedValues) {

    allowedValues = new Set(allowedValues)
    // Return the result of the filter.

    return source.filter(item => {
    // Returns true when `a` is present in vals, otherwise it returns false.
       return allowedValues.has(item.a);
    });
}
const filteredArray = filterByValue(objs, vals);

console.log(filteredArray)




相关问题