skip to Main Content

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


  1. It might be more readable to use every() on Object.values(obj.options)

    const obj = {
        options: {
            opt1: { value: '', state: false },
            opt2: { value: '', state: false },
            opt3: { value: '', state: false },
        }
    }
    
    const everyOptionHasEmptyValue = Object.values(obj.options).every(o => o.value === '');
    console.log(everyOptionHasEmptyValue); // true
    Login or Signup to reply.
  2. There are two problems in your code:

    1. You are actually looping over the whole object which is this obj and this is wrong because obj has only one "key value pair" which is the options object and so when you loop over the whole obj you are NOT checking "values" inside of the options object. Instead what you should do is to loop over the obj.options object.

    2. 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 here

    Before writing the solution, look at the result of this when we use Object.entries(object) for an object:

    const object = {
    a: 12,
    b: 'hi',
    }
    
    console.log(Object.entries(object)) 
    // Object.entries(object) = [['a', 12], ['b', 'hi']]
    

    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:

    for (const [key, value] of Object.entries(obj.options)) {
     if (value !== null && value !== '') return false;
     else return true;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search