Return 使用下划线从数组中创建一个新数组
Return a new array from an array using Underscore
我想return一个仅包含指定值的过滤数组
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"});
你可以很好地使用过滤器,但你的对象有一些语法错误。值必须在字符串中。显示此示例:
var messages=[ {
id: 1,
name: "John",
hashtag: ["#cool"] },
{id: 2,
name: "Bob",
hashtag: ["#cool"," #sweet"] },
{id: 3,
name: "Bob",
hashtag: ["#sweet"]
}];
var newArray=messages.filter(function(task){ return task.hashtag.includes("#cool") });
console.log(newArray);
这里有一个纯函数式的方法,你可以用下划线来做,不过,更喜欢 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>
您不能使用 _.where
过滤存储在 "hashtag" 中的数组(因为它在键值对中搜索字符串)但您可以使用 _.filter
var filtered = _.filter( messages, function( message ){
return message['hashtag'].indexOf('#cool') !== -1;
} );
演示它工作的小代码笔:https://codepen.io/iwantwin/pen/oGWNzv
我想return一个仅包含指定值的过滤数组
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"});
你可以很好地使用过滤器,但你的对象有一些语法错误。值必须在字符串中。显示此示例:
var messages=[ {
id: 1,
name: "John",
hashtag: ["#cool"] },
{id: 2,
name: "Bob",
hashtag: ["#cool"," #sweet"] },
{id: 3,
name: "Bob",
hashtag: ["#sweet"]
}];
var newArray=messages.filter(function(task){ return task.hashtag.includes("#cool") });
console.log(newArray);
这里有一个纯函数式的方法,你可以用下划线来做,不过,更喜欢 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>
您不能使用 _.where
过滤存储在 "hashtag" 中的数组(因为它在键值对中搜索字符串)但您可以使用 _.filter
var filtered = _.filter( messages, function( message ){
return message['hashtag'].indexOf('#cool') !== -1;
} );
演示它工作的小代码笔:https://codepen.io/iwantwin/pen/oGWNzv