Find a value in json object using lodash methods flatten and find

一世执手 提交于 2020-01-24 10:21:19

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!