Filtering array of objects by searching nested object properties

后端 未结 6 715
执笔经年
执笔经年 2020-12-06 07:38

I have an array of objects that I want to filter by comparing a nested property to a search term.

For example:

 var array = [
      {category: \'Bus         


        
6条回答
  •  臣服心动
    2020-12-06 07:52

    You could use Array#filter with looking into the nested arrays by using Array#some.

    If the tag is found in a nested array, then iteration stops and the result is given back to the filter callback.

    var array = [{ category: 'Business', users: [{ name: 'Sally', tags: [{ tag: 'accounting' }, { tag: 'marketing' }] }, { name: 'Bob', tags: [{ tag: 'sales' }, { tag: 'accounting' }] }] }, { category: 'Heritage', users: [{ name: 'Linda', tags: [{ tag: 'Italy' }, { tag: 'Macedonia' }] }, { name: 'George', tags: [{ tag: 'South Africa' }, { tag: 'Chile' }] }] }],
        tag = 'marketing',
        result = array.filter(a => a.users.some(u => u.tags.some(t => t.tag.includes(tag))));
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题