JS:If语句检查数组中是否存在var

问题描述 投票:-1回答:1

我有一个AngularJS应用程序,我在其中定义了一组有一组经销商的数组。像这样的东西:

     $scope.dealers = [{
            name: "Dealer Name",
            address: "Address goes here",
            website:"site.com",
            lat: "latitude",
            lng: "longitude"
            territory: ['County1', 'County2', 'County3']
          },
          {
            name: "Dealer Name",
            address: "Address goes here",
            website:"site.com",
            lat: "latitude",
            lng: "longitude",
            territory: ['County1', 'County2', 'County3']
              }, 
    ];

用户将输入他们的邮政编码,然后使用谷歌地理编码API,我将他们的邮政编码转换为纬度/经度坐标,并根据他们与所有经销商之间的坐标找到他们最近的经销商。

这工作正常。

这是我需要帮助的地方。在找到最近的经销商之前,每个经销商都有一个领域(在阵列中作为县)需要首先检查,因为一些经销商在其所在地区的县实际上在地理位置上更靠近另一个经销商。

我有一个var,根据他们的zip存储用户县。所以我需要制作一个IF语句,检查来自dealer数组的userZip变量,以查看该县是否存在于数组中的任何位置。如果是,那么我需要返回该经销商的名称。如果没有,我将有一个ELSE语句,只运行我已经拥有的功能,这将找到最接近他们位置的经销商。

javascript arrays angularjs json
1个回答
2
投票

你可以使用Array.prototype.find()

let dealers = [{
    name: "Dealer Name",
    address: "Address goes here",
    website: "site.com",
    lat: "latitude",
    lng: "longitude",
    territory: ['County1', 'County2', 'County3']
  },
  {
    name: "Dealer Name",
    address: "Address goes here",
    website: "site.com",
    lat: "latitude",
    lng: "longitude",
    territory: ['County1', 'County2', 'County3']
  },
];

let country = 'County2';
let found = dealers.find(d => d.territory.includes(country));

if(found)
  console.log(found);
else
  console.log("..find closest...");


//another case
country = 'NotAnywhere';
found = dealers.find(d => d.territory.includes(country));

if(found)
  console.log(found);
else
  console.log("..find closest...");
© www.soinside.com 2019 - 2024. All rights reserved.