通过搜索嵌套对象属性来过滤对象数组 [英] Filtering array of objects by searching nested object properties

查看:67
本文介绍了通过搜索嵌套对象属性来过滤对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组,我想通过将嵌套属性与搜索词进行比较来进行过滤.

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

例如:

 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'},...]
                 },...
               ]
       },...
    [

基本上,我想通过一个搜索词来过滤对象的基本数组,这些搜索词包括嵌套对象2个数组以下的标签属性字符串中的字符.

Essentially I want to filter the base array of objects by a search terms that include characters from the tag property string in the nested objects 2 arrays down.

因此,搜索市场"将导致

So a search for 'market' would result in

[
  {category: 'Business'
   users: [
            {name: 'Sally'
             tags: [{tag: 'accounting'}, {tag: 'marketing'},...]
            },
            {name: 'Bob'
             tags: [{tag: 'sales'}, {tag: 'accounting'},...]
            }...
          ]
   }
]

谢谢.

推荐答案

您可以使用

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

这篇关于通过搜索嵌套对象属性来过滤对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆