Search code examples
javascriptnested-object

Javascript check all values of object and it's nested object


Hi i'm currently stuck with this problem of checking an object that has another nested object if all value in it is null or 0

My object is as follow:

{
   "city":0,
   "road":{
      "max":null,
      "min":null
   },
   "size":{
      "max":null,
      "min":null
   },
   "type":null,
   "ward":0,
   "floor":null,
   "price":{
      "max":null,
      "min":null
   },
   "street":0,
   "toilet":null,
   "balcony":null,
   "bedroom":null,
   "district":0,
   "frontend":{
      "max":null,
      "min":null
   },
   "direction":null,
   "living_room":null
}

i need to check every single values in it is 0 or null , return true if all values is either 0 or null, false if any of the values different than null or 0

i can't use :

Object.values(object).every(i => (i === null || i === ''))

It return False since the nested object still consider as a different value than 0 and null

I don't want to write super long if condition check every single value of it at a time

Is there anyway to iterate over the object and it's nested object to check ?


Solution

  • You could take an iterative and recursive approach.

    function check(object) {
        return Object.values(object).every(v => v && typeof v === 'object'
            ? check(v)
            : v === 0 || v === null
        );
    }
    
    var data0 = { city: 0, road: { max: null, min: null }, size: { max: null, min: null }, type: "sell", ward: 0, floor: null, price: { max: null, min: null }, street: 0, toilet: null, balcony: null, bedroom: null, district: 0, frontend: { max: null, min: null }, direction: null, living_room: null },
        data1 = { city: 0, road: { max: null, min: null }, size: { max: null, min: null }, type: null, ward: 0, floor: null, price: { max: null, min: null }, street: 0, toilet: null, balcony: null, bedroom: null, district: 0, frontend: { max: null, min: null }, direction: null, living_room: null };
    
    console.log(check(data0)); // false because of type: "sell"
    console.log(check(data1)); // true