从数组中过滤对象,具有匹配两个值的差异

问题描述 投票:1回答:2

我有一个数组,我想用另一个数组过滤。我的目标是使用两个值过滤数组,我希望结果只与这两个值完全匹配。这是我到目前为止:

const array = [
  {
    title: 'Title A',
    someOtherProps: [
      'AAA',
    ]
  }, {
    title: 'Title B',
    someOtherProps: [
      'AAA',
      'BBB',
    ]
  }, {
    title: 'Title C',
    someOtherProps: [
      'BBB',
      'CCC'
    ]
  }, {
    title: 'Title D',
    someOtherProps: [
      'BBB',
    ]
  }, {
    title: 'Title E',
    someOtherProps: [
      'CCC'
    ]
  },
]

const filter = [
  'AAA',
  'BBB',
]

let result = array.filter(obj => obj.someOtherProps.some(props => filter.includes(props)))
console.log(result);

所以我的结果是具有我的过滤值的对象。

// My Result
{
  title: 'Title A'
  someOtherProps: [
    'AAA',
  ]
}, {
  title: 'Title B'
  someOtherProps: [
    'AAA',
    'BBB',
  ]
}, {
  title: 'Title C'
  someOtherProps: [
    'BBB',
    'CCC'
  ]
}, {
  title: 'Title D'
  someOtherProps: [
    'BBB',
  ]
}

到现在为止还挺好。但我不需要所有具有其中一个值的对象。我需要对象,它正好结合了这两个值。

// Wanted Result
{
  title: 'Title B'
  someOtherProps: [
    'AAA',
    'BBB',
  ]
}

我找不到办法。我知道如何获得两个数组的差异。但如果你知道我的意思,我需要两个值的区别。

javascript arrays filter
2个回答
3
投票

Array#every()数组上使用filter并检查其所有值是否包含在对象的someOtherProps中。如果只需要一个对象,可以使用Array#find()

const array = [ { title: 'Title A', someOtherProps: [ 'AAA', ] }, { title: 'Title B', someOtherProps: [ 'AAA', 'BBB', ] }, { title: 'Title C', someOtherProps: [ 'BBB', 'CCC' ] }, { title: 'Title D', someOtherProps: [ 'BBB', ] }, { title: 'Title E', someOtherProps: [ 'CCC' ] }, ]

const filter = ['AAA','BBB',]

let res = array.find(x => filter.every( a => x.someOtherProps.includes(a)));
console.log(res)

如果你想要所有匹配条件的元素,那么使用filter()

const array = [ { title: 'Title A', someOtherProps: [ 'AAA', ] }, { title: 'Title B', someOtherProps: [ 'AAA', 'BBB', ] }, { title: 'Title C', someOtherProps: [ 'BBB', 'CCC' ] }, { title: 'Title D', someOtherProps: [ 'BBB', ] }, { title: 'Title E', someOtherProps: [ 'CCC' ] }, ]

const filter = ['AAA','BBB',]

let res = array.filter(x => filter.every( a => x.someOtherProps.includes(a)));
console.log(res)

0
投票

改变:

array.filter(x => filter.every( a => x.someOtherProps.includes(a)));
© www.soinside.com 2019 - 2024. All rights reserved.