0

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);
  }
1
  • hi { el.cityName === "Durban"} should be { return el.cityName === "Durban"} or can be just `el.cityName === "Durban". You are very close :-) Commented Jul 31, 2018 at 4:40

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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");

1 Comment

or even .find and then just check for null

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.