5

I have an object with this kind of structure.

const object = {
  property1: null,
  property2: {
    array1: [],
    array2: []
  },
  property3: {
    prop1: null,
    prop2: null
  }
}

I need to check every property in object or each value in each property and if it is falsy - null, or empty array then do someting with it. Otherwise just leave it.

I'm not sure how to do it considering some properties have nested properties etc.

All help will be much appreciated.

Person
  • 2,190
  • 7
  • 30
  • 58
  • Simple recursive function, that calls itself again with the current property value, if that property is an array or object …? – misorude Oct 11 '18 at 11:02
  • 2
    I'm a bit surprised that this got 3 upvotes. It's certainly lacking effort – Liam Oct 11 '18 at 11:03

3 Answers3

0

You can use for...in loop to achieve this:

const object1 = {
  property1: null,
  property2: false,
  prop3: "hello",
  prop4: 1234
}

for (let attr in object1) {
  if (!object1[attr]) {
    console.log(attr, "this is false");
  } else {
    console.log(attr, "has a value");
  }
}
messerbill
  • 5,499
  • 1
  • 27
  • 38
  • This needs a `hasOwnProperty` check or else your going to get unexpected results – Liam Oct 11 '18 at 11:01
  • What happens if you have more than one level of nesting, like the example? – VLAZ Oct 11 '18 at 11:11
  • if you have a "n-level-nested" structure you need to recurse through it as long as the recursive function may detect further nested objects – messerbill Oct 11 '18 at 11:37
0

You could take an iterative and recursive approach.

First take the entries of the object and iterate the key/value pairs. Then check if the value is null or en empty array. If so, do something, like console.log and return the callback.

If not check for an object and call the function again with the actual value.

function iter(object) {
    Object
      .entries(object)
      .forEach(([k, v]) => {
          if (v === null || Array.isArray(v) && !v.length) {
              console.log(k, 'is null or empty');
              return;
          }
          if (v && typeof v === 'object') {
              iter(v);
          }
      });
}

const object = { property1: null, property2: { array1: [], array2: [] }, property3: { prop1: null, prop2: null } };

iter(object);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

That would be a perfect example for a recursion, as it would dynamically go deeper into the object structure for every nested object.

const object = {
  property1: null,
  property2: {
    array1: [],
    array2: []
  },
  property3: {
    prop1: null,
    prop2: null
  }
}

const findFalsey = obj => {
    for(let key in obj) {
        if(typeof obj[key] === 'object' && !Array.isArray(obj[key])) {
            findFalsey(obj[key])
        }
        if(!obj[key] || (Array.isArray(obj[key]) && obj[key].length === 0 )) {
            console.log('found falsey value')
        }
    }
}

findFalsey(object)
noa-dev
  • 3,561
  • 9
  • 34
  • 72