我有一个包含以下内容的数组
var people = [{
_id: 0,
name: 'Joe'
}, {
_id: 1,
name: 'Jim'
}, {
_id: 2,
name: 'Mary'
}];
所以使用lodash,我想从people
创建一个数组,其中名称包含J
任何想法?
例如:
var newPeople = _.filter(people, function(person) {
return _.contains('J', person.name);
});
甚至更好:
var newPeople = _(people).map(_.unary(_.partialRight(_.contains, 'J', 'name'))).value();
上述任何功能版本都会很棒。提前谢谢。
答案 0 :(得分:1)
这有效:
var newPeople = _.filter(people, function(person) {
return person.name.indexOf('J') >= 0;
});
对于你的其他方式:
var contains = function (obj, str, elem) {
if (obj[elem].indexOf(str) >= 0) {
return obj;
}
return;
}
newPeople = _(people).map(_.unary(_.partialRight(contains, 'J', 'name'))).compact().sortBy('name').value();
答案 1 :(得分:0)
不需要lodash进行比较。例如,这有效:
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.3.0/lodash.js"></script>
<script>
var people = [{
_id: 0,
name: 'Joe'
}, {
_id: 1,
name: 'Jim'
}, {
_id: 2,
name: 'Mary'
}];
var newPeople = _.filter(people, function(person) {
return person.name.indexOf('J') > -1;
});
console.log(newPeople);
</script>