为了账号安全,请及时绑定邮箱和手机立即绑定

在对象数组中搜索特定值并返回多个结果

在对象数组中搜索特定值并返回多个结果

慕姐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 关注
  • 73 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信