[英]how to use lodash to find specific result in collection?
I am working on lodash ...I want to find particular array if matching id mind in that particular array...This is my collection:- 我正在lodash上工作...如果要匹配特定数组中的id思维,我想找到特定数组...这是我的收藏:-
[ { name: 'Thor',
id:
[ '5a1676da509a93571c15501f',
'59ffb40f62d346204e09c9ad',
'5a0a92e01bb28a276abfa548' ] },
{ name: 'Loki',
id:
[ '59ffb40f62d346204e09c9ad',
'59ffb41b62d346204e0a03ed',
'59ffb40e62d346204e09c298',
'5a65853af431924e73c401fe' ] } ]
What I am trying to find i have given id if it should find it above collection then it should return that collection...for example..if i have id:59ffb40e62d346204e09c298,then it should return 2 collection..... 我试图找到的是我给定的id,如果它应该在集合上方找到它,那么它应该返回那个集合...例如..如果我有id:59ffb40e62d346204e09c298,那么它应该返回2个集合.....
b = _.find(upperArray,(candidate) => {
// console.log(candidate)
return _.find(candidate.id,id)//here actor_id is given id
})
but it does not return 2 collection.If it does not found any matching element it should return blank array or if found it should return collection of array.Where I am doing wrong?? 但它不返回2 collection。如果未找到任何匹配的元素,则应返回空白数组,或者如果找到应返回array的集合。我在哪里做错了?
Using can achieve the same using native array methods 使用本机数组方法可以实现相同的效果
var id = "59ffb40e62d346204e09c298"; var arr = [{ name: 'Thor', id: ['5a1676da509a93571c15501f', '59ffb40f62d346204e09c9ad', '5a0a92e01bb28a276abfa548' ] }, { name: 'Loki', id: ['59ffb40f62d346204e09c9ad', '59ffb41b62d346204e0a03ed', '59ffb40e62d346204e09c298', '5a65853af431924e73c401fe' ] } ] function getMatchedCollection(id) { // filter will return a new array of matched condition return arr.filter(function(item) { // indexOf is used to check if an element is present if (item.id.indexOf(id) !== -1) { return item } }) } console.log(getMatchedCollection(id))
@Barmar is correct you should use _.filter
. @Barmar是正确的,您应该使用_.filter
。 Try the following 尝试以下
var upperArray = [ { name: 'Thor', id: [ '5a1676da509a93571c15501f', '59ffb40f62d346204e09c9ad', '5a0a92e01bb28a276abfa548' ] }, { name: 'Loki', id: [ '59ffb40f62d346204e09c9ad', '59ffb41b62d346204e0a03ed', '59ffb40e62d346204e09c298', '5a65853af431924e73c401fe' ] } ]; function findById(idToFind) { return _.filter(upperArray,function(candidate) { return _.includes(candidate.id, idToFind); }); } var b = findById('59ffb40e62d346204e09c298'); console.log(b);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.