有这样一个数据数组。如何使用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
}]
答案 0 :(得分:1)
You can use Array.filter()
and 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)
or lodash equivalents:
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>
答案 1 :(得分:0)
Why use lodash if js already offers everything you need?
const items = terms.filter(item => item.parentIds && item.parentIds.includes(myParentId));
答案 2 :(得分:0)
You can use filter
in combination with includes
to filter out the entries where parentIds
contains a certain id.
function filter(id) {
return _.filter(terms, term => term.parentIds.includes(id));
}
Also, you do not need lodash:
function filter(id) {
return terms.filter(term => term.parentIds.includes(id));
}