我有一个嵌套的JSON结构:
[
{
name: 'some name',
type: 'type1',
collection: ['one', 'two', 'three']
},
{
name: 'another name',
type: 'type1',
collection: ['one', 'two']
},
{
name: 'third name',
type: 'type2',
collection: ['two']
}
]
我试图编写一个lodash _.filter语句(尽可能简单),我可以在其中过滤类型等字符串属性,但也可以过滤数组属性,如集合检查它是否包含某些值。例如,我想找到type
type1
collection
并且one
数组包含值two
和typeof
的所有对象}。
这种类型的东西是否有速记,或者我是不是写了一个函数来做一些cat1 cat2
->sub1 ->sub1
->sub2 ->sub1_1
->sub3
->sub3_1
->sub3_2
->sub3_2_1
->sub3_2_2
->sub4
sub4_1
-sub5
体操来确定属性值类型,然后相应地进行比较?
答案 0 :(得分:0)
_.filter(arr, item => {
const hasCollection = item.collection && item.collection.indexOf('one') > -1 && item.collection.indexOf('two') > -1;
return item.type === 'type1' && hasCollection;
});
答案 1 :(得分:0)
使用_.matches
的_.filter
简写在过滤时执行部分深度比较:
var array = [{"name":"some name","type":"type1","collection":["one","two","three"]},{"name":"another name","type":"type1","collection":["one","two"]},{"name":"third name","type":"type2","collection":["two"]}];
var filtered = _.filter(array, {
type: 'type1',
collection: ['one', 'two']
});
console.log(filtered);
<script src="https://cdn.jsdelivr.net/lodash/4.15.0/lodash.min.js"></script>