我想返回仅包含指定值的过滤数组

var messages: [{
     id: 1,
     name: "John",
     hashtag: ["#cool"]},

     {id: 2,
     name: "Bob",
     hashtag: ["#cool", "#sweet"]},

     {id: 3,
     name: "Bob",
     hashtag: ["#sweet"]} ];

// supposed to return the first two items in the array
var newArray = _.where(messages, {hashtag: "#cool"});

最佳答案

这是您可以通过下划线实现的一种纯粹的功能方式,但是,更喜欢Ramda进行这种事情:



var messages = [{
    id: 1,
    name: "John",
    hashtag: ["#cool"]
  },

  {
    id: 2,
    name: "Bob",
    hashtag: ["#cool", "#sweet"]
  },

  {
    id: 3,
    name: "Bob",
    hashtag: ["#sweet"]
  }
]

var newArray = _.filter(messages, _.compose(_.partial(_.contains, _, '#cool'), _.property('hashtag')))

console.log(newArray)

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

10-07 14:30