有这样一个数据阵列。如何使用lodash方法_.filter实现parentTd(数组“parentIds”之一)的过滤?
"terms": [{
"id": 13,
"name": 'illustrator',
"parentIds": [2, 4],
"isCompanyArea": false
},
{
"id": 14,
"name": 'figma',
"parentIds": [2, 3],
"isCompanyArea": true
},
{
"id": 15,
"name": 'sas',
"parentIds": [3 ,4, 2],
"isCompanyArea": false
},
{
"id": 16,
"name": 'jmp',
"parentIds": [3],
"isCompanyArea": false
},
{
"id": 17,
"name": 'docker',
"parentIds": [4, 5],
"isCompanyArea": false
}]
您可以将filter
与includes
结合使用,以过滤掉parentIds
包含特定ID的条目。
function filter(id) {
return _.filter(terms, term => term.parentIds.includes(id));
}
此外,你不需要lodash:
function filter(id) {
return terms.filter(term => term.parentIds.includes(id));
}
你可以使用Array.filter()
和Array.includes()
:
const getAllChildrenById = searchParentId =>
terms.filter(({ parentIds }) => parentIds.includes(searchParentId))
const terms = [{"id":13,"name":"illustrator","parentIds":[2,4],"isCompanyArea":false},{"id":14,"name":"figma","parentIds":[2,3],"isCompanyArea":true},{"id":15,"name":"sas","parentIds":[3,4,2],"isCompanyArea":false},{"id":16,"name":"jmp","parentIds":[3],"isCompanyArea":false},{"id":17,"name":"docker","parentIds":[4,5],"isCompanyArea":false}]
const result = getAllChildrenById(4)
console.log(result)
或者lodash等价物:
const searchParentId = searchParentId =>
_.filter(terms, ({ parentIds }) => _.includes(parentIds, searchParentId))
const terms = [{"id":13,"name":"illustrator","parentIds":[2,4],"isCompanyArea":false},{"id":14,"name":"figma","parentIds":[2,3],"isCompanyArea":true},{"id":15,"name":"sas","parentIds":[3,4,2],"isCompanyArea":false},{"id":16,"name":"jmp","parentIds":[3],"isCompanyArea":false},{"id":17,"name":"docker","parentIds":[4,5],"isCompanyArea":false}]
const result = searchParentId(4)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
如果js已经提供了你需要的一切,为什么要使用lodash?
const items = terms.filter(item => item.parentIds && item.parentIds.includes(myParentId));