how to filtering javascript array of objects

前端 未结 3 1498
生来不讨喜
生来不讨喜 2021-01-29 10:34

I have got two arrays . I am filtering based groupKey with PubSidebar.

3条回答
  •  孤独总比滥情好
    2021-01-29 10:51

    If I understand correctly you want to filter PubSidebar. Keeping values if they have a role of public or a value of whats included in the groupKey. If so this would be your function:

    PubSidebar.filter(x => (x.role === 'public' || groupKey.includes(x.value));
    

    If you want to run that on content as well we could pull it apart:

    const filterByGroup = (x) => (x.role === 'public' || groupKey.includes(x.value));
    
    let result = [];
    for (let i = 0; i < PubSidebar.length; i++) {
      const item = PubSidebar[i];
    
      if (filterByGroup(item)) {
        if (item.content) {
          item.content = item.content.filter(filterByGroup);
        }
        result = [ ...result, item ];
      }
    }
    

    Snippet:

    let groupKey = ['oaDeal', 'Journals', 'Deposit']
    const PubSidebar = [{
        value: 'Dashboard',
        role: 'public',
      },
      {
        value: 'oaDeal',
        role: 'private',
        content: [{
          role: 'private',
          value: 'oaDeal',
        }, ],
      },
      {
        value: 'Journals',
        role: 'public',
        content: [{
            role: 'private',
            value: 'Journals',
          },
          {
            role: 'private',
            value: 'Token',
          },
          {
            role: 'private',
            value: 'policy',
          },
          {
            role: 'private',
            value: 'Deposit',
          },
          {
            role: 'public',
            value: 'test'
          },
        ],
      },
    ]
    
    const filterByGroup = (x) => (x.role === 'public' || groupKey.includes(x.value));
    
    let result = [];
    for (let i = 0; i < PubSidebar.length; i++) {
      const item = PubSidebar[i];
    
      if (filterByGroup(item)) {
        if (item.content) {
          item.content = item.content.filter(filterByGroup);
        }
        result = [...result, item];
      }
    }
    console.log(result);

提交回复
热议问题