I am working on lodash ...I want to find particular array if matching id mind in that particular array...This is my collection:-
[ { 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.....
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??
答案 0 :(得分:0)
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))
答案 1 :(得分:0)
@Barmar is correct you should use _.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>