在数组中查找现有对象

时间:2018-07-31 04:21:48

标签: javascript arrays angular

我有以下数组

[{cityName: "Gauteng"}, {cityName: "cape town"}, {cityName: "Durban"}]

我正在尝试检查任何对象中的值是否与“ cityName” 相匹配。例如,我将值设置为“ Durban”,并且由于Durban存在于其中,它应该返回true。对象

我的尝试在下面,但是即使cityName存在,我也会得到一个错误的值

  test() {
   var x = this.getCities;
   var doesExist = x.some((el) => { el.cityName === "Durban"});
   console.log(doesExist);
  }

2 个答案:

答案 0 :(得分:2)

工作正常。您的x变量可能为null。我猜getCities应该是一个函数

var x = this.getCities();

演示

let cities = [{cityName: "Gauteng"}, {cityName: "cape town"}, {cityName: "Durban"}];
let isFound = cities.some(t=>t.cityName ==='Durban');
console.log(isFound);

答案 1 :(得分:1)

您也可以尝试

let cities = [{cityName: "Gauteng"}, {cityName: "cape town"}, {cityName: "Durban"}];
const index = cities.findIndex(t=>t.cityName ==='Durban');
if(index !== -1 )
  console.log("found");

或按照建议的方式查找

let cities = [{cityName: "Gauteng"}, {cityName: "cape town"}, {cityName: "Durban"}];
const foundelement = cities.find(t=>t.cityName ==='Durban');
if(foundelement)
  console.log("found");