3

I have the following object, and want to set all the values in it to null, while maintaining the objects structure

var objs = {
    a: {
        prop1: {id: null, val: 10},
        prop2: true,
        prop3: null,
    },
    b: {
        prop1: {id: null, val: 20},
        prop2: true,
        prop3: null,
    },
    c: 10
}

The results needs to be:

var objs = {
    a: {
        prop1: {id: null, val: null},
        prop2: null,
        prop3: null,
    },
    b: {
        prop1: {id: null, val: null},
        prop2: null,
        prop3: null,
    },
    c: null
}

This solution works for me, and I believe it should work for any depth. But if there is more elegant or efficient solution, please let me know.

var objs = {
    a: {
        prop1: {id: null, val: 10},
        prop2: true,
        prop3: null,
    },
    b: {
        prop1: {id: null, val: 20},
        prop2: true,
        prop3: null,
    },
    c: 10
}

function nullTest(val){
    for (key in val) {
        if(typeof(val[key]) !== 'object') {
            val[key] = null;
        } else {
            val[key] = nullTest(val[key])
        }
    }
    return val
}

console.log(nullTest(objs));

Thanks

0

1 Answer 1

4

You can use Object.keys to get all the keys of the object, loop over them using forEach, and recurse accordingly.

var objs = {
    a: {
        prop1: {id: null, val: 10},
        prop2: true,
        prop3: null,
    },
    b: {
        prop1: {id: null, val: 20},
        prop2: true,
        prop3: null,
    },
    c: 10
}
function nullTest(val){
    return Object.keys(val).forEach(k=>val[k]=val[k]===Object(val[k])?nullTest(val[k]):null), val;
}
console.log(nullTest(objs));

You can use Array.prototype.reduce to create a new object without modifying the old one.

const objs = {
    a: {
        prop1: {id: null, val: 10},
        prop2: true,
        prop3: null,
    },
    b: {
        prop1: {id: null, val: 20},
        prop2: true,
        prop3: null,
    },
    c: 10
};
function nullTest(val){
    return Object.keys(val).reduce((acc,key)=>(acc[key]=val[key]===Object(val[key])?nullTest(val[key]):null,acc),{});
}
console.log('new object:', nullTest(objs));
console.log('objs:', objs);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.