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

前端 未结 7 531
北荒
北荒 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 15:52

    let values = {
        a:1, 
        b:'', 
        c: {
            a:'', 
            s:4, 
            d: {
                q: '',
                w: 8,
                e: 9
            }
     
        }
    }
    
    
    values;
    
    const completeWithNull = (current) => {
      Object.keys(current).forEach((key) => {
       		current[key] = current[key] === ''? null 
        	: typeof current[key] === 'object' ? completeWithNull(current[key])
        	: current[key]
      });
      
      return current;
    };
    
    completeWithNull(values);

提交回复
热议问题