【问题标题】:JS - filter array of objects by array of property values and return array of filtered objectsJS - 通过属性值数组过滤对象数组并返回过滤对象数组
【发布时间】:2017-09-06 22:54:25
【问题描述】:

我正在尝试(在 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() - 一个迭代对象数组,第二个迭代属性值数组,但我认为这是最后一个选项 - 寻找更优雅、更短的东西。大家有什么想法吗?

【问题讨论】:

    标签: arrays filter find javascript-objects


    【解决方案1】:

    您可以使用 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)

    【讨论】:

      【解决方案2】:

      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)

      【讨论】:

        猜你喜欢
        • 2019-08-22
        • 1970-01-01
        • 2019-05-29
        • 2019-07-18
        • 1970-01-01
        • 2019-05-04
        • 2021-10-02
        • 1970-01-01
        相关资源
        最近更新 更多