如何使用underscoreJS过滤对象数组?

时间:2018-04-26 22:51:16

标签: javascript arrays underscore.js

(已解决,请在回复中检查解决方案)

问题:

我有一个对象数组,我希望能够只过滤那些与我指定的对象相同的对象,我已经尝试了很多方法,但最后我最终获得了相同的空数组。

我认为数组返回空,因为我在一个对象数组上迭代而不是在一个简单的数组上。

在这里,我展示了我的代码:

我还放置了undercoreJS文档中显示的过滤器示例

(点击按钮显示此结果)



$(document).ready(function() {

  /*
   *   START - My Filter using Underscore.js
   *
   */
  var arrObject = [{
    "data": [{
        "img": "test1"
      },
      {
        "img": "test2"
      },
      {
        "img": "/image_folder/sub_folder/886.jpg"
      }
    ]
  }];

  var compare = [{
    "img": "/image_folder/sub_folder/886.jpg"
  }];

  var finalArray;

  //console.log(arrObject);
  //console.log(compare);

  $.each(arrObject, function(index, element) {
    //console.log(element.data);
    finalArray = _.filter(element.data, function(ev) {
      return ev == compare;
    });
  });

  console.log(finalArray);

  /*
   *   END - My Filter using Underscore.js
   *
   */




  /*
   *   START - ORIGINAL Filter from Documentation Underscore.js
   *
   */
  $(document).on("click", ".originalUnderscore", function() {
      var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) {
      return num % 2 == 0;
    });
    console.log(evens);
  });
  /*
   *   END - ORIGINAL Filter from Documentation Underscore.js
   *
   */

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

<button class="originalUnderscore">Click to show the original filter</button>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

首先,在将对象比较为_.isMatch(...)时,应使用===仅比较参考号 其次,您将对象element.data[0]与数组compare进行比较

所以你的代码应该是这样的:

&#13;
&#13;
$(document).ready(function() {
  const arrObject = [{
    "data": [{
        "img": "test1"
      },
      {
        "img": "test2"
      },
      {
        "img": "/image_folder/sub_folder/886.jpg"
      }
    ]
  }];

  const compare = {
    "img": "/image_folder/sub_folder/886.jpg"
  };

  $('.filterBtn').on('click', () => {
    let filtredArray = [];
    $.each(arrObject, (index, element) => {
      filtredArray = _.filter(element.data, function(ev) {
        return _.isMatch(ev, compare);
      });
      console.log(`filtredArray from data in element at index ${index}`);
      console.log(filtredArray);
    });
  });
});
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

<button class="filterBtn">Click filter</button>
&#13;
&#13;
&#13;