[英]How to check if array of objects contains any value from array
Hi so i have an array of integers which i have been trying to check against my array of objects.嗨所以我有一个整数数组,我一直在尝试检查我的对象数组。 I only want to check that ANY of the values in the array are within the objArray, it does not need to be ALL.
我只想检查数组中的任何值是否在 objArray 内,它不需要是 ALL。
const objArray = [{id: 1},{id: 2},{id: 3}]
const array = '1,2'
This is what i tried but i think i am probably way off the logic, i end up getting false every time i run the below code.这是我尝试过的,但我认为我可能不符合逻辑,每次运行以下代码时我最终都会出错。
stringToArray(array).includes(objArray.some(o => o.id))
Essentially my overall goal to is to validate that any return true and then continue with code otherwise throw an error.本质上,我的总体目标是验证任何返回 true,然后继续执行代码,否则会引发错误。
function stringToArray() {
return valueString.match( /(?=\S)[^,]+?(?=\s*(,|$))/g )
}
Thanks for you help?谢谢你的帮助? I keep getting false regardless and it may be to do with my function wrapping around the array,.
不管怎样,我一直在出错,这可能与我的 function 环绕数组有关。 My array was originally a string which i converted using regex to an array.
我的数组最初是一个字符串,我使用正则表达式将其转换为数组。
Thank you in advance!先感谢您!
You're very close.你很亲密。 Just flip your statement around.
只需翻转你的陈述。
objArray.some(o => array.includes(o.id))
const objArray = [{id: 1},{id: 2},{id: 3}] const array = [1, 2]; console.log(objArray.some(o => array.includes(o.id)));
You were on the right track with your logic.你的逻辑是正确的。
Although this is not the most efficient answer, it will work for ur case.虽然这不是最有效的答案,但它适用于您的情况。
I believe you want to match all of the values, if I understand you correctly.如果我理解正确的话,我相信你想要匹配所有的值。
Therefore, one way to check if each id in the object is included in the array is to loop over the object.因此,检查 object 中的每个 id 是否包含在数组中的一种方法是遍历 object。
If you want to much at least one, just change it to some
instaed of every
如果您至少想要
some
,只需将其更改为every
const objArray = [{id: 1},{id: 2},{id: 3}] const array = [1, 2,3] const condition = objArray.every(objElement => { // here you get acess to id here. so we check it againts the array return array.includes(objElement.id) }) console.log(condition)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.