How to Find an Element in a JavaScript Object?

Estimated read time 1 min read

To find an element in a JavaScript object, you can use a for loop to iterate over the properties of the object, and then compare the properties with the element you are looking for.

Here’s an example:

const object = {
  key1: "value1",
  key2: "value2",
  key3: "value3"
};

const findElement = (object, element) => {
  for (let key in object) {
    if (object[key] === element) {
      return key;
    }
  }
  return undefined;
};

console.log(findElement(object, "value2")); // Output: "key2"

In this example, the findElement function takes two arguments: an object and an element. It uses a for loop to iterate over the properties of the object and compares the properties with the element. If the property is equal to the element, the function returns the key of that property. If the element is not found, the function returns undefined.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply