问题
Using lodash i want to find a team whose id is 3229. I tried following but it is not returning anything.
var team = _.chain(data.teams)
.flatten("divisionTeams")
.find({"id":3229})
.value();
Here is my plunker code.
http://plnkr.co/edit/UDwzRkX3zkYjyf8UwO7I
For the Json data please see the file data.js in Plunker.
Please note i cannot change the json data since i am calling a test api.
回答1:
flatten doesn't take that argument, see docs. You need to either map or pluck the divisionTeams.
_.chain(data.teams)
.pluck('divisionTeams')
.flatten()
.find({id: 3232})
.value();
回答2:
So if the requirements are to only use flatten, find, and lodash, that's going to be difficult. But using a for loop to get the division teams might be what you're asking.
var teams = [];
for(var e of data.teams) {
teams.push(e.divisionTeams);
}
var blah = _.flatten(teams, true);
console.log(_.find(blah, function(item) { return item.id == 3222; }));
来源:https://stackoverflow.com/questions/29090260/find-a-value-in-json-object-using-lodash-methods-flatten-and-find