How to implement the 'getAllChildrenById' method

梦想与她 提交于 2019-12-13 09:19:35

问题


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": '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
    }]

回答1:


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



回答2:


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>



回答3:


Why use lodash if js already offers everything you need?

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


来源:https://stackoverflow.com/questions/55814153/how-to-implement-the-getallchildrenbyid-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!