javascript - 循环遍历数组并检查其中的数组是否具有特定值

标签 javascript arrays filter foreach

我有一个如下所示的对象数组

const arr = 
  [ { a: '', b: '', arr: [ { label: '2' }, { label: '3' }                 ] } 
  , { a: '', b: '', arr: [ { label: '1' }, { label: '2' }, { label: '3' } ] } 
  , { a: '', b: '', arr: [ { label: '1' }, { label: '3' }                 ] } 
  ] 

我需要过滤这个数组并获取arr数组中标签值为2的对象。

即,预期结果:

const arr = 
  [ { a: '', b: '', arr: [ { label: '2' }, { label: '3' }                 ] } 
  , { a: '', b: '', arr: [ { label: '1' }, { label: '2' }, { label: '3' } ] } 
  ] 

我尝试过这样的事情:

array.forEach((item) => item.arr.filter(i) => i.label === '2')

我们如何返回一个循环遍历该数组的过滤数组,该数组在 arr 数组内的标签值为“2”?

怎样才能达到预期的效果?

最佳答案

使用过滤器一些解构

const arr = 
  [ { a: '', b: '', arr: [ { label: '2' }, { label: '3' }                 ] } 
  , { a: '', b: '', arr: [ { label: '1' }, { label: '2' }, { label: '3' } ] } 
  , { a: '', b: '', arr: [ { label: '1' }, { label: '3' }                 ] } 
  ]
  
const output = arr.filter(({ arr }) => arr.some(({ label }) => label === '2'));
  
console.log(output)

关于javascript - 循环遍历数组并检查其中的数组是否具有特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73494297/

相关文章:

javascript - Node.JS fork 管道

javascript - 排列需要帮助编码

java - 使用模板方法模式设计过滤器接口(interface)

javascript - 私有(private)函数不返回值

javascript - 使用 jquery 加载二进制图像

javascript - 将 vec2 数组传递给 THREE.js 中的着色器

arrays - 循环数组 - 无法调用追加

java - 在第三个数组内打印两个数组,该数组的组合长度与前两个数组的长度相同

ios:NSFetchRequest 和过滤

c# - 同态滤波器输出