我想返回一个只包含指定值的过滤数组
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>
关于javascript - 使用下划线从数组返回一个新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46455227/