How to set all values of an object to null in JavaScript?

前端 未结 7 544
北荒
北荒 2021-01-01 15:03

I need to set all properties of some object to null. But the object can be very big, so I can\'t just do it one by one.

How to set all properties at onc

7条回答
  •  北荒
    北荒 (楼主)
    2021-01-01 16:00

    Lodash can manage this using cloneDeepWith.

    My solution to the same problem:

    import * as _ from 'lodash';
    const bigObj = {"big": true, "deep": {"nested": {"levels": "many" } } };
    const blankObj = _.cloneDeepWith(bigObj, (value) => {return _.isObject(value) ? undefined : null});
    console.log(blankObj);
    // outputs { big: null, deep: { nested: { levels: null } } }
    

    Returning undefined in the customizer was not obvious to me, but this answer explains that doing so triggers recursion.

提交回复
热议问题