我有一个如下所示的对象数组
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/