Javascript 在对象数组中搜索特定值并返回多个结果
我需要找到多个数组中具有特定值的所有对象,并返回此图像中所有匹配对象的另一个值 我会尝试用一个例子让它更清楚一点。我正在搜索每个Javascript 在对象数组中搜索特定值并返回多个结果,javascript,arrays,object,ecmascript-6,Javascript,Arrays,Object,Ecmascript 6,我需要找到多个数组中具有特定值的所有对象,并返回此图像中所有匹配对象的另一个值 我会尝试用一个例子让它更清楚一点。我正在搜索每个目标,并返回源值。 有些数组有匹配的对象,有些可能没有。结果数组应具有唯一的值 const deps = { "something": [ { "type": "static", "source": "foo", "
目标
,并返回源
值。
有些数组有匹配的对象,有些可能没有。结果数组应具有唯一的值
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
只会给我一个结果(这是一个对象)。如何获取所有结果而不是第一个匹配对象?将Array.find()
替换为可以返回多个结果的Array.filter()
:
const-deps={“某物”:[{“类型”:“静态”,“源”:“foo”,“目标”:“bar”},{“类型”:“静态”,“源”:“返回我”,“目标”:“找到我”}],“任何东西”:[{“类型”:“静态”,“源”:“和我”,“目标”:“找到我”}],“不匹配”:[{“类型”:“静态”,“源”:“foo”,“目标”:“bar”}]
const search='找到我'
常量源=对象
.价值观(deps)
.flat()
.filter(el=>el.target==搜索)
.map(el=>el.source)
console.log(sources)
将Array.find()
替换为可以返回多个结果的Array.filter()
:
const-deps={“某物”:[{“类型”:“静态”,“源”:“foo”,“目标”:“bar”},{“类型”:“静态”,“源”:“返回我”,“目标”:“找到我”}],“任何东西”:[{“类型”:“静态”,“源”:“和我”,“目标”:“找到我”}],“不匹配”:[{“类型”:“静态”,“源”:“foo”,“目标”:“bar”}]
const search='找到我'
常量源=对象
.价值观(deps)
.flat()
.filter(el=>el.target==搜索)
.map(el=>el.source)
console.log(sources)
而不是使用Array.find
,您需要使用Array.filter
来获得匹配的结果
const deps={
“某物”:[
{
“类型”:“静态”,
“来源”:“foo”,
“目标”:“条”
},
{
“类型”:“静态”,
“来源”:“返回我”,
“目标”:“找到我”
}
],
“任何东西”:[
{
“类型”:“静态”,
“来源”:“和我”,
“目标”:“找到我”
}
],
“不匹配”:[
{
“类型”:“静态”,
“来源”:“foo”,
“目标”:“条”
}
]
};
常量结果=对象值(deps)
.flat()
.filter(({target})=>target==='find me')
.map(({source})=>source);
控制台日志(结果)
而不是使用数组。查找
,您需要使用数组。过滤器
来获得匹配的结果
const deps={
“某物”:[
{
“类型”:“静态”,
“来源”:“foo”,
“目标”:“条”
},
{
“类型”:“静态”,
“来源”:“返回我”,
“目标”:“找到我”
}
],
“任何东西”:[
{
“类型”:“静态”,
“来源”:“和我”,
“目标”:“找到我”
}
],
“不匹配”:[
{
“类型”:“静态”,
“来源”:“foo”,
“目标”:“条”
}
]
};
常量结果=对象值(deps)
.flat()
.filter(({target})=>target==='find me')
.map(({source})=>source);
控制台日志(结果)代码>