简体   繁体   English

在两个数组中查找匹配值

[英]finding matching values in two arrays

So I have this value I am getting back from an API that could either be a single item or multiple items. 所以我有这个价值,我从一个可以是单个项目或多个项目的API回来了。

I map over and return the value I want. 我映射并返回我想要的值。

const value = JSONObject.map(data => {return data.value});

console.log(value); // ["value"]

or multiple strings if more than one value present in the map. 或多个字符串(如果映射中存在多个值)。

Now comes the part where I am confused. 现在是我感到困惑的部分。

I have another local JSON Object that I want to match against the value from the api. 我有另一个本地JSON对象,我想与api中的值进行匹配。

for(i = 0; i < LocalJSONObject; i++;){
 if(value === LocalJSONObject[i].value){
 console.log("matching values")
 }
}

Only thing is "value" is an array that can contain one single string item or multiple string items. 唯一的是“值”是一个可以包含一个或多个字符串项的数组。

My understanding is the above if statement is comparing an array to a string which would never be true and thus it never logs. 我的理解是上述if语句将数组与字符串进行比较,该字符串永远不会为真,因此永远不会记录日志。

How do I get it to compare the value in the value array? 如何获取比较值数组中的值?

for (var lo = 0; lo < LocalJSONObject.length; ++lo) {
  for (var va = 0; va < value.length; ++va) {
    if (value[va] === LocalJSONObject[lo].value) {
      console.log('Matching values:', value[va]);
    }
  }
}

Yes, you are correct in assuming that your statement is comparing an array to a string because the map method returns an array. 是的,假设您的语句正在将数组与字符串进行比较,这是正确的,因为map方法返回了数组。

To solve it efficiently, you can use the Array.prototype.includes() method to get the result. 为了有效地解决它,可以使用Array.prototype.includes()方法获取结果。

for(i = 0; i < LocalJSONObject; i++;){
 if(value.includes(LocalJSONObject[i].value)){
   console.log("matching values")
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM