亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

JS:過濾對象列表以僅包含在第二個數組中找到的字符串

JS:過濾對象列表以僅包含在第二個數組中找到的字符串

慕少森 2022-09-29 10:24:04
我有一個類似于以下內容的對象數組:let array = [{id: 1,name: Foo,tools: [{id:3, toolname: Jaw},{id:1, toolname: Law}]},{id: 2,name: Boo,tools: [{id:2, toolname: Caw}]},{id: 3,name: Loo,tools: [{id:3, toolname: Jaw}, {id:4, toolname: Maw}, {id:6, toolname: Taw}]}]我有第二個數組,如下所示:let secondarray = ['Jaw', 'Taw']如何返回僅包含第二個數組中兩個項目的對象列表?因此,如果一個對象只有兩者中的一個,則不會包含該對象。此外,如果對象包含其他不在 中,但同時包含 兩項,則仍應包含它。toolssecondarraysecondarray因此,此濾波器的預期輸出為:{id: 3,name: Loo,tools: [{id:3, toolname: Jaw}, {id:4, toolname: Maw}, {id:6, toolname: Taw}]}感謝您抽出寶貴時間接受采訪!
查看完整描述

1 回答

?
波斯汪

TA貢獻1811條經驗 獲得超4個贊

您可以迭代數據數組,然后檢查所有需要的工具是否都在實際對象中。


let array = [{ id: 1, name: 'Foo', tools: [{ id: 3, toolname: 'Jaw' }, { id: 1, toolname: 'Law' }] }, { id: 2, name: 'Boo', tools: [{ id: 2, toolname: 'Caw' }] }, { id: 3, name: 'Loo', tools: [{ id: 3, toolname: 'Jaw' }, { id: 4, toolname: 'Maw' }, { id: 6, toolname: 'Taw' }] }],

    required = ['Jaw', 'Taw'],

    result = array.filter(({ tools }) =>

        required.every(v => tools.some(({ toolname }) => toolname === v))

    );


console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


另一種通過使用 Set 多次省略循環的方法。tools


let array = [{ id: 1, name: 'Foo', tools: [{ id: 3, toolname: 'Jaw' }, { id: 1, toolname: 'Law' }] }, { id: 2, name: 'Boo', tools: [{ id: 2, toolname: 'Caw' }] }, { id: 3, name: 'Loo', tools: [{ id: 3, toolname: 'Jaw' }, { id: 4, toolname: 'Maw' }, { id: 6, toolname: 'Taw' }] }],

    required = ['Jaw', 'Taw'],

    result = array.filter(({ tools }) => 

        required.every(

            Set.prototype.has,

            new Set(tools.map(({ toolname }) => toolname))

        )

    );


console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


查看完整回答
反對 回復 2022-09-29
  • 1 回答
  • 0 關注
  • 123 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號