I have the following Array
[{cityName: "Gauteng"}, {cityName: "cape town"}, {cityName: "Durban"}]
I am trying to check if a value matches "cityName" in any of the objects .eg I have a set value as "Durban" and it should return true as Durban exists in on of the objects
My attempt is below however I am getting a false value even if the cityName exists
test() {
var x = this.getCities;
var doesExist = x.some((el) => { el.cityName === "Durban"});
console.log(doesExist);
}
It works fine. Probably your x variable is null. I guess getCities should be a function
var x = this.getCities();
DEMO
let cities = [{cityName: "Gauteng"}, {cityName: "cape town"}, {cityName: "Durban"}]; let isFound = cities.some(t=>t.cityName ==='Durban'); console.log(isFound);
you can try this also
let cities = [{cityName: "Gauteng"}, {cityName: "cape town"}, {cityName: "Durban"}];
const index = cities.findIndex(t=>t.cityName ==='Durban');
if(index !== -1 )
console.log("found");
or find as suggested in commen t
let cities = [{cityName: "Gauteng"}, {cityName: "cape town"}, {cityName: "Durban"}];
const foundelement = cities.find(t=>t.cityName ==='Durban');
if(foundelement)
console.log("found");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.