我在后端工作,我有一个大数据的列表,我有另一个列表,我想找到它存在于biiger列表或不。如果它存在那么它应该返回空数组,否则它应该只返回唯一元素。 我的大清单是这样的:
[ { name: 'Kapil',
_id: 59ffb40d62d346204e09c0c1,
tags: [] },
{ name: 'Nitin',
_id: 59ffb40d62d346204e09c0d9,
tags: [] },
{ name: 'Rakesh',
_id: 5a0180b0d76afa5eaa79db05,
tags: [] },
{much more} ]
和我希望在更大的列表中找到它的列表:
[{ name: 'Neelesh',
_id: 59ffb40d62d346204easdwd9,
tags: [] },
{ name: 'Rakesh',
_id: 5a0180b0d76afa5eaa79db05,
tags: [] }]
然后它应该只返回这个结果:
{ name: 'Neelesh',
_id: 59ffb40d62d346204easdwd9,
tags: [] }
因为它不在大名单中。 我的lodash脚本是这样的:
_.filter(my_given_list,(item) => (_.find(bigger_list,{name:item.name})))
但它没有给出我预期的结果。我在哪里做错了?
答案 0 :(得分:0)
正如@charlietfl所说,它应该是!_.find(..
来过滤已经在大列表中的项目。我跑了那个代码并且效果很好。
var bigList =
[
{
name: 'Kapil',
_id: "59ffb40d62d346204e09c0c1",
tags: []
},
{
name: 'Nitin',
_id: "59ffb40d62d346204e09c0d9",
tags: []
},
{
name: 'Rakesh',
_id: "5a0180b0d76afa5eaa79db05",
tags: []
}
]
var myList =
[
{
name: 'Neelesh',
_id: "59ffb40d62d346204easdwd9",
tags: []
},
{
name: 'Rakesh',
_id: "5a0180b0d76afa5eaa79db05",
tags: []
}
]
var result = _.filter( myList,
( item ) => ( !_.find( bigList, { name:item.name } ) )
)
console.log( result )
结果
[[object Object] {
_id: "59ffb40d62d346204easdwd9",
name: "Neelesh",
tags: []
}]
答案 1 :(得分:0)
您可以使用_.differenceBy()
(在您的情况下为name
或_id
)查找myList
中存在的项目,但不要退出bigList
:
var bigList = [{"name":"Kapil","_id":"59ffb40d62d346204e09c0c1","tags":[]},{"name":"Nitin","_id":"59ffb40d62d346204e09c0d9","tags":[]},{"name":"Rakesh","_id":"5a0180b0d76afa5eaa79db05","tags":[]}]
var myList = [{"name":"Neelesh","_id":"59ffb40d62d346204easdwd9","tags":[]},{"name":"Rakesh","_id":"5a0180b0d76afa5eaa79db05","tags":[]}]
var result = _.differenceBy(myList, bigList, '_id')
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>