javascript 按属性筛选对象数组中的对象数组[已关闭]

798qvoo8  于 2022-12-28  发布在  Java
关注(0)|答案(1)|浏览(172)

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
19小时前关门了。
Improve this question
我有一个具有不同属性(国家,名称)的对象数组(allItems)。国家是对象内的数组,我需要通过searchByCountry参数进行过滤,该参数只是一个国家的名称(字符串),例如'Germany'。

var allItems = [{
  name: 'Item1',
  countries: [
      {label: 'Argentina', TermGuid: 'abc'},
      {label: 'Germany', TermGuid: 'abc'},
      {label: 'Bosnia', TermGuid: 'abc'},
      {label: 'France', TermGuid: 'abc'},
      {label: 'UK', TermGuid: 'abc'}
    ]
  },
  {
   name: 'Item2',
   countries: [
    {label: 'Argentina', TermGuid: 'abc'}
   ]
  },
  {
   name: 'Item3',
   countries: [
    {label: 'Bosnia', TermGuid: 'abc'}
   ]
  },
  {
   name: 'Item4',
   countries: [
    {label: 'All', TermGuid: 'abc'}
   ]
  }
]

    
var searchByCountry = 'Bosnia';

因此,"波斯尼亚"的预期产量为:

var allItems = [{
  name: 'Item1',
  countries: [
      {label: 'Argentina', TermGuid: 'abc'},
      {label: 'Germany', TermGuid: 'abc'},
      {label: 'Bosnia', TermGuid: 'abc'},
      {label: 'France', TermGuid: 'abc'},
      {label: 'UK', TermGuid: 'abc'}
    ]
  },
  {
   name: 'Item3',
   countries: [
    {label: 'Bosnia', TermGuid: 'abc'}
   ]
  }
]
fdbelqdn

fdbelqdn1#

通过使用数组过滤器和一些方法,这应该可以实现:

var allItems = [{
    name: 'Item1',
    countries: [{
        label: 'Argentina',
        TermGuid: 'abc'
      },
      {
        label: 'Germany',
        TermGuid: 'abc'
      },
      {
        label: 'Bosnia',
        TermGuid: 'abc'
      },
      {
        label: 'France',
        TermGuid: 'abc'
      },
      {
        label: 'UK',
        TermGuid: 'abc'
      }
    ]
  },
  {
    name: 'Item2',
    countries: [{
      label: 'Argentina',
      TermGuid: 'abc'
    }]
  },
  {
    name: 'Item3',
    countries: [{
      label: 'Bosnia',
      TermGuid: 'abc'
    }]
  },
  {
    name: 'Item4',
    countries: [{
      label: 'All',
      TermGuid: 'abc'
    }]
  }
]

var searchByCountry = 'Bosnia';

const filtered = allItems.filter(item => item.countries.some(country => country.label === searchByCountry))

console.log(filtered)

相关问题