Skip to content Skip to sidebar Skip to footer

How To Implement The 'getallchildrenbyid' Method

There is such an array of data. How do I implement filtering by parentTd (one of the array 'parentIds'), using lodash method _.filter? 'terms': [{ 'id': 13, 'name': 'i

Solution 1:

You can use Array.filter() and Array.includes():

constgetAllChildrenById = 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:

constsearchParentId = 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)
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

Solution 2:

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));
}

Solution 3:

Why use lodash if js already offers everything you need?

const items = terms.filter(item => item.parentIds && item.parentIds.includes(myParentId));

Post a Comment for "How To Implement The 'getallchildrenbyid' Method"