[英]What would be the best way to check if any of the keys in an array of objects contain a value from an object of arrays array?
I want to create a filter system by checking if any of the project technologies exist in the arrOfObjs.name
's.我想通过检查
arrOfObjs.name
存在任何项目技术来创建过滤系统。 If it does, then it will pass the filter and be included/shown to the DOM.如果是,那么它将通过过滤器并被包含/显示到 DOM。 More specifically a computed value in VueJS.
更具体地说,是 VueJS 中的计算值。
Example:例子:
arrOfObjs = [{name: 'test1', image: 'testing1'}, {name: 'test2', image:'testing2'}]
projects:
[
{
name: "testproject",
description: "lorem ipsum",
technologies: ["test2", "test7", "test3"]
},
{
name: "atest",
description: "lorem ipsum",
technologies: ["test1", "test2", "test5"]
},
]
My attempt:我的尝试:
computed: {
myComputedVal () {
projs = []
this.projects.forEach(p => {
p.technologies.forEach(t => {
this.arrOfObjs.filter(o => {
if (o.name == t) {
return p // maybe projs = [...projs, p] and return projs
}
})
})
})
}
}
I want to check if ANY of the values in technologies exist in arrOfObjs.name
, if it does, then return the project or push it to an array to later return this array of objects as a computed value.我想检查
arrOfObjs.name
中是否存在技术中的任何值,如果存在,则返回项目或将其推送到一个数组,以便稍后将此对象数组作为计算值返回。 At the moment, nothing happens.目前,什么都没有发生。
I think with the below code snippet you can filter out those projects where any of the technologies
are present in the arrOfObjs
array's name
properties.我认为使用下面的代码片段,您可以过滤掉那些在
arrOfObjs
数组的name
属性中存在任何technologies
项目。
Using flatMap()
you can get all the names into an array as strings first.使用
flatMap()
您可以首先将所有名称作为字符串放入数组中。 Then using filter()
as you wanted originally and with using some()
and includes()
combination just filter out the projects if any of the technologies elements are represented in names
array like:然后按照您最初的需要使用
filter()
并使用some()
和includes()
组合,如果任何技术元素在names
数组中表示,则只需过滤掉项目,例如:
({technologies}) => technologies.some(t => names.includes(t))
If you would like to check if all the elements are present, then suggest to use every()
like:如果您想检查所有元素是否都存在,那么建议使用
every()
例如:
({technologies}) => technologies.every(t => names.includes(t))
Possible solution - representing the example with some()
:可能的解决方案 - 用
some()
表示示例:
const arrOfObjs = [{name: 'test1', image: 'testing1'}, {name: 'test2', image:'testing2'}], projects = [{name: "testproject",description: "lorem ipsum",technologies: ["test2", "test7", "test3"]}, {name: "atest",description: "Lorem ipsum", technologies: ["test1", "test2", "test5"] }]; const names = arrOfObjs.flatMap(e => e.name); const result = projects.filter( ({technologies}) => technologies.some(t => names.includes(t) // technologies.every(t => names.includes(t) // if all needed ) ); console.log(result);
I hope that helps!我希望这有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.