如何将JSON数据与数组localy进行比较

时间:2018-06-07 15:18:24

标签: javascript json

我的脚本中有一些对象:

var data =
[
            {
            "name":"United Kingdom",
            "countryCode":"GB",
            "urlCode":"en-gb",
            "standardPrice":"30"
        },{
            "name":"Germany",
            "countryCode":"DE",
            "urlCode":"de-de",
            "standardPrice":"22"
        }

];

我想比较" urlCode"到我已经拥有的数组让我们说它叫做array1

我想访问上面的这些数据并将其与我的数组进行比较,说明这个数组是否与数据中的urlCode匹配,显示匹配的数据中的所有对象。

2 个答案:

答案 0 :(得分:1)

尝试以下方法:

var data =
[
            {
            "name":"United Kingdom",
            "countryCode":"GB",
            "urlCode":"en-gb",
            "standardPrice":"30"
        },{
            "name":"Germany",
            "countryCode":"DE",
            "urlCode":"de-de",
            "standardPrice":"22"
        }

];
var arr =["de-de"];
data.forEach((o) =>{
  if(arr.includes(o.urlCode))
    console.log(o);
});

答案 1 :(得分:-3)

您可以按元素逐个比较:

your_array = ['en-gb','de-de']
data = [
            {
            "name":"United Kingdom",
            "countryCode":"GB",
            "urlCode":"en-gb",
            "standardPrice":"30"
        },{
            "name":"Germany",
            "countryCode":"DE",
            "urlCode":"de-de",
            "standardPrice":"22"
        }
];
isEqual = True
for i in range(0,len(data)):
    if  data[i]['urlCode'] != your_array[i]:
        isEqual = False
        break
print isEqual