我们有一个对象数组
var myArr = [ {name: "john", age:23}
{name: "john", age:43}
{name: "jim", age:101}
{name: "bob", age:67} ];
如何从lAash获取myArr中名称为john的对象列表?
答案 0 :(得分:96)
使用lodash _.filter
方法:
_.filter(collection, [predicate=_.identity])
迭代集合的元素,返回所有元素的数组谓词返回truthy。使用三个参数调用谓词: (value,index | key,collection)。
将谓词作为自定义函数
_.filter(myArr, function(o) {
return o.name == 'john';
});
谓词作为过滤对象的一部分(_.matches
iteratee简写)
_.filter(myArr, {name: 'john'});
谓词为[key,value] array (_.matchesProperty
iteratee简写。)
_.filter(myArr, ['name', 'John']);
答案 1 :(得分:18)
Lodash有一个“map”功能,就像jQuerys:
一样
var app = angular.module('plunker', []);
app.controller('MainCtrl', ['tempDataStorageService', function(tempDataStorageService) {
var register = this;
register.firstName = "";
register.storedData = tempDataStorageService;
register.test = function () {
tempDataStorageService.setName(register.firstName);
}
}]);
app.factory('tempDataStorageService', function() {
// The service object
var profile = {};
profile.doctorFirstName = "No doctor data stored";
//The functions
profile.setName = function(data) {
profile.doctorFirstName = data;
}
profile.getName = function() {
return profile.doctorFirstName;
}
// return the service object
return profile;
});
答案 2 :(得分:3)
let myArr = [
{name: "john", age:23},
{name: "john", age:43},
{name: "jim", age:101},
{name: "bob", age:67},
];
// this will return old object (myArr) with items named 'john'
let list = _.filter(myArr, item => item.name === 'jhon');
// this will return new object referenc (new Object) with items named 'john'
let list = _.map(myArr, item => item.name === 'jhon').filter(item => item.name);
答案 3 :(得分:2)
let myArr = [
{name: "john", age:23},
{name: "john", age:43},
{name: "jim", age:101},
{name: "bob", age:67},
];
let list = _.filter(myArr, item => item.name === "john");
答案 4 :(得分:1)
const myArr = [ {name: "john", age:23},
{name: "john", age:43},
{name: "jim", age:101},
{name: "bob", age:67} ];
const johnArr = _.filter(myArr, person => person.name === 'john');
console.log(johnArr)
const myArr = [ {name: "john", age:23},
{name: "john", age:43},
{name: "jim", age:101},
{name: "bob", age:67} ];
const johnArr = myArr.filter(person => person.name === 'john');
console.log(johnArr);
答案 5 :(得分:1)
**按姓名,年龄过滤** 另外,您可以使用地图功能
地图和过滤器之间的差异
1。 map -map()方法创建一个新数组,并为每个数组元素调用一个函数。 map方法允许根据用户的喜好对数组中的项目进行操作,从而在全新的数组中返回所选操作的结论。例如,考虑以下数组:
2。 filter -filter()方法创建一个数组,该数组填充了所有通过提供的函数实现的测试的数组元素。筛选方法非常适合于特定情况,在这些情况下,用户必须标识数组中具有共同特征的某些项目。例如,考虑以下数组:
`const users = [
{name: "john", age:23},
{name: "john", age:43},
{name: "jim", age:101},
{name: "bob", age:67}
];
const user = _.filter(users, {name : 'jim', age: 101});
console.log(user);`
答案 6 :(得分:0)
lodash还具有删除方法
var myArr = [ {name: "john", age:23}
{name: "john", age:43}
{name: "jim", age:101}
{name: "bob", age:67} ];
var onlyJohn = myArr.remove( person => { return person.name == "john" })