get keys wher value is true in object in javascript

How to Get Keys Where Value is True in an Object in JavaScript

Have you ever needed to retrieve the keys of an object where the value is true? This can be useful in many scenarios, such as filtering data or checking for conditions. In this article, we'll explore different ways to achieve this in JavaScript.

Method 1: Using a for...in loop

The simplest way to get the keys where the value is true is by using a for...in loop. This method loops through each key in the object and checks if the corresponding value is true. If it is, the key is added to an array.

const obj = {
  a: true,
  b: false,
  c: true,
  d: false
};

let trueKeys = [];

for (const key in obj) {
  if (obj[key]) {
    trueKeys.push(key);
  }
}

console.log(trueKeys); // Output: ["a", "c"]

In the above code, we define an object with four keys and corresponding boolean values. We then create an empty array to store the true keys. Next, we loop through each key in the object and check if its value is true. If it is, we push the key to the trueKeys array. Finally, we log the array to the console.

Method 2: Using the Object.keys() method with filter()

Another way to get the keys where the value is true is by using the Object.keys() method along with the filter() method. This method creates a new array with all elements that pass the test implemented by the provided function. In this case, we use it to filter out the keys where the value is false.

const obj = {
  a: true,
  b: false,
  c: true,
  d: false
};

let trueKeys = Object.keys(obj).filter(key => obj[key]);

console.log(trueKeys); // Output: ["a", "c"]

In this code, we define an object with four keys and corresponding boolean values. We then use the Object.keys() method to create an array of keys from the object. Next, we use the filter() method to filter out the keys where the value is false. Finally, we log the resulting array to the console.

Conclusion

There are many ways to get the keys of an object where the value is true in JavaScript. The for...in loop and Object.keys() method with filter() are just two examples. Choose the method that best suits your needs and use it to get the desired result.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe