'parse value from array of object: error undefined is not iterable

I would like to get the value from array under of object and also provide some error checking. I have following code to check if key exist and if value of key is array type or not. if yes, I would like to get the value from the key. it seems ok, but any better way I can get value? I tried to use const [value] = obj?.the_key but get exception Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator)) if value from the_key is not array or the_key does not exist under object

const obj = {'theKey': ['correct value']}
const hasKey = obj['theKey'] !== undefined && Array.isArray(obj.theKey)
if (!hasKey) console.log('null')
const [value] = obj.theKey
console.log(value)


Solution 1:[1]

You can use the hasOwnProperty and isArray functions to check if your object has the key / property that you are looking for.

const obj = { 'theKey' : ['correct value'] };

let hasKey = obj.hasOwnProperty('theKey'); // This will return true / false

if (!hasKey) { // key does not exist

   // error handling logic

}

Then you can check the data type of the value if it is array or not

if (hasKey) {

   let keyVal = obj.theKey;

   if (Array.isArray(keyVal)) { // returns true or false

      // business logic with array

   } else { // key value is not array

      // error handling

   }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Raja