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

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

在對象數組中搜索特定值并返回多個結果

在對象數組中搜索特定值并返回多個結果

慕姐4208626 2023-04-27 16:44:47
我需要在多個數組中找到具有特定值的所有對象,返回所有匹配對象的圖像的另一個值。我會嘗試用一個例子讓它更清楚一點。我正在搜索每個target具有值的值find-me并獲取source返回值。有些數組有匹配的對象,有些可能沒有。結果數組應具有唯一值。const deps = {  "something": [    {      "type": "static",      "source": "foo",      "target": "bar"    },    {      "type": "static",      "source": "return-me",      "target": "find-me"    }  ],  "anything": [    {      "type": "static",      "source": "and-me",      "target": "find-me"    }  ],  "no-match": [    {      "type": "static",      "source": "foo",      "target": "bar"    }  ]}所以對于這個例子,結果應該是['return-me', 'and-me']我試過這個:const search = 'find-me'const sources = Object  .values(deps)  .flat()  .find(el => el.target === search)  .map(el => el.source)但這當然行不通,因為find只會給我一個結果(這是一個對象)。如何獲得所有結果而不是第一個匹配的對象?
查看完整描述

2 回答

?
素胚勾勒不出你

TA貢獻1827條經驗 獲得超9個贊

而不是使用Array.find,您需要使用Array.filter來獲得匹配的結果。


const deps = {

  "something": [

    {

      "type": "static",

      "source": "foo",

      "target": "bar"

    },

    {

      "type": "static",

      "source": "return-me",

      "target": "find-me"

    }

  ],

  "anything": [

    {

      "type": "static",

      "source": "and-me",

      "target": "find-me"

    }

  ],

  "no-match": [

    {

      "type": "static",

      "source": "foo",

      "target": "bar"

    }

  ]

};


const result = Object.values(deps)

  .flat()

  .filter(({ target }) => target === 'find-me')

  .map(({ source }) => source);

console.log(result);


查看完整回答
反對 回復 2023-04-27
?
DIEA

TA貢獻1820條經驗 獲得超2個贊

替換Array.find()為Array.filter()可以返回多個結果:


const deps = {"something":[{"type":"static","source":"foo","target":"bar"},{"type":"static","source":"return-me","target":"find-me"}],"anything":[{"type":"static","source":"and-me","target":"find-me"}],"no-match":[{"type":"static","source":"foo","target":"bar"}]}


const search = 'find-me'

const sources = Object

  .values(deps)

  .flat()

  .filter(el => el.target === search)

  .map(el => el.source)

  

console.log(sources)


查看完整回答
反對 回復 2023-04-27
  • 2 回答
  • 0 關注
  • 135 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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