accessing whether a value is inside an Object or not

Viewed 35

how can i know if a value is in my object in Js, I don't know how to explain it exactly but I hope the code simplifies it for you

let object = {
  1: hey
  2: hi
  3: hello
}
let exist = object.value("hello")
console.log(exist) //should print true
3 Answers

let object = {
  1: "hey",
  2: "hi",
  3: "hello"
}
let exist = Object.values(object).includes("hello")
console.log(exist)

There are plenty of ways to check if a value is contained within an object.

A simple one is by accessing the Object.values(myObject).

Should look like this:

console.log(Object.values(myObject).some(elem => (elem === ('hello'))));
// true

You can use Object.values

let object = {
  1: "hey",
  2: "hi",
  3: "hello"
}
   
let exists = Object.values(object).includes("hello");
console.log(exists);
exists = Object.values(object).includes("world");
console.log(exists);

But if you need checks like this quite often, you should probably think about a data structure better supporting that scenario ...

Related