[英]Filter array of objects where one object's array has at least one match with another array
我提前道歉,無法為數據提供更好的示例。
所以我有數組things
,它目前只包含一個包含id
屬性的對象和一個只包含我突然想到的隨機事物/單詞的數組,以及other_things
,以及來自things
數組的一些隨機單詞。
let things=[ { id: 1, names: ['car','door','chair'] }, { id: 2, names: ['cat','dog','door'] }, { id: 3, names: ['phone','mouse','cat'] }, { id: 4, names: ['building','desk','pen'] }, { id: 5, names: ['road','date','number'] } ]; let other_things=['car','door','pen'];
我想要實現的是過濾數組things
,並且只獲取那些對象/元素,其中names
數組至少包含other_things
數組中的一個元素。
在這個例子中,只有things[2]
和things[4]
與other_things
中的任何單詞都不匹配,所以我們不需要它們。
我已經嘗試了很多東西,比如結合 ES6 方法,比如filter
, every
或map
,嘗試使用嵌套for
循環,但不幸的是沒有任何結果。
let things=[ { id: 1, names: ['car','door','chair'] }, { id: 2, names: ['cat','dog','door'] }, { id: 3, names: ['phone','mouse','cat'] }, { id: 4, names: ['building','desk','pen'] }, { id: 5, names: ['road','date','number'] } ]; let other_things=['car','door','pen']; console.log(things.filter(t => t.names.filter(n => other_things.includes(n)).length > 0))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.