Home > Enterprise >  Efficient way to check nested properties in object are truthy?
Efficient way to check nested properties in object are truthy?

Time:01-22

Basically is there an easy way to write 'If any of these properties are null, treat the whole object as null/don't return.' for instances where I'm mapping a lot of properties to a new object.

const object = {
one: {a: 'a',
            b: 'b',
            c: {
                c1: 'c1',
                c2: null}
            },
}
// if properties of object !== null
return {
    myObject: {
        myA: object.a,
        myC1: object.c.c1
        myC2: object.c.c2
        ...
    }
}
//else return something else

I'd prefer to not have to write a huge conditional to get around this.

CodePudding user response:

Using recursion you can quickly get a boolean that indicates whether or not there is a null value in an object.

matchNULLValue will return true every time it finds a null-valued property, this goes for nested objects as well.

const object = {
    one: {
        a: 'a',
        b: 'b',
        c: {
            c1: 'c1',
            c2: null
        }
    },
}

function matchNULLValue(object) {
    for (const value of Object.values(object)) {
        if (value === null || (typeof value === "object" && matchNULLValue(value))) {
            return true;
        }
    }

    return false;
}

if (matchNULLValue(object)) {
    console.log("There is some property on this object with null value.");
} else {
    console.log("There is no property on this object with a null value.");
}

CodePudding user response:

function containsNull(obj) {
    for (let key in obj) {
        if (obj[key] === null) {
            return true;
        } else if (typeof obj[key] === "object") {
            return checkNull(obj[key]);
        }
    }
    return false;
}

You can have a recursive function to perform the task. This function returns true if any of the object contains null.

  •  Tags:  
  • Related