I need to determine whether object key value is empty or not in nested object. Below is the nested object. As you can see, in the options object I have multiple object and I have to check if ‘value’ key is empty for entire object then it should return true.
const obj = {
options: {
opt1: {
value: '',
state: false,
},
opt2: {
value: '',
state: false,
},
opt3: {
value: '',
state: false,
},
}
}
I have tried below approach
for (const key in obj) {
if (obj[key].value !== null && obj[key].value !== '')
return false;
return true;
}
May be above approach required bit refactor.
2
Answers
It might be more readable to use
every()
onObject.values(obj.options)
There are two problems in your code:
You are actually looping over the whole object which is this
obj
and this is wrong becauseobj
has only one "key value pair" which is the options object and so when you loop over the wholeobj
you are NOT checking "values" inside of the options object. Instead what you should do is to loop over theobj.options
object.Objects are not iterable and you can not loop over them and instead, you should try to convert them to something iterable (like arrays) and then loop over them and you can do this with
Object.entries()
which will pack key value pairs inside of an object inside an array. You can read about it on mdn hereBefore writing the solution, look at the result of this when we use
Object.entries(object)
for an object:So Object.entries basically gives an array of arrays in which that each of the nested arrays contain the key and the related value of it.
So by knowing all of this:
You can achieve what you need like this: