we have an object in javascript that consists of key and values. we want to get keys…
- User
we have an object in javascript that consists of key and values. we want to get keys that their value is not empty or "".
- Assistant
To get the keys with non-empty values, you can use a loop to iterate over all the key-value pairs and check if the value is not empty or "". Here's an example:
const myObject = { key1: '', key2: 'hello', key3: 123, key4: '', } const nonEmptyKeys = Object.keys(myObject).filter(key => { const value = myObject[key] return (value !== '' && value !== null && value !== undefined) }) console.log(nonEmptyKeys) // Output: ["key2", "key3"]In this example, we first define an object
myObjectwith four key-value pairs. We then useObject.keysto get an array of all the keys inmyObject. We use thefiltermethod to iterate over these keys and return only those where the corresponding value is non-empty.The
value !== '' && value !== null && value !== undefinedcondition checks for three different cases. First, we make sure that the value is not an empty string (''). Second, we check whether the value is null. Third, we check if the value is undefined.The final result is an array of non-empty keys:
["key2", "key3"].