How to quickly clear a JavaScript Object?

后端 未结 8 1128
一个人的身影
一个人的身影 2020-11-27 12:52

With a JavaScript Array, I can reset it to an empty state with a single assignment:

array.length = 0;

This makes the Array \"appear\" empty

8条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 13:25

    This bugged me for ages so here is my version as I didn't want an empty object, I wanted one with all the properties but reset to some default value. Kind of like a new instantiation of a class.

    let object1 = {
      a: 'somestring',
      b: 42,
      c: true,
      d:{
        e:1,
        f:2,
        g:true,
        h:{
          i:"hello"
        }
      },
      j: [1,2,3],
      k: ["foo", "bar"],
      l:["foo",1,true],
      m:[{n:10, o:"food", p:true }, {n:11, o:"foog", p:true }],
      q:null,
      r:undefined
    };
    
    let boolDefault = false;
    let stringDefault = "";
    let numberDefault = 0;
    
    console.log(object1);
    //document.write("
    ");
    //document.write(JSON.stringify(object1))
    //document.write("
    "); cleanObject(object1); console.log(object1); //document.write(JSON.stringify(object1)); //document.write("
    "); function cleanObject(o) { for (let [key, value] of Object.entries(o)) { let propType = typeof(o[key]); //console.log(key, value, propType); switch (propType) { case "number" : o[key] = numberDefault; break; case "string": o[key] = stringDefault; break; case "boolean": o[key] = boolDefault; break; case "undefined": o[key] = undefined; break; default: if(value === null) { continue; } cleanObject(o[key]); break; } } } // EXPECTED OUTPUT // Object { a: "somestring", b: 42, c: true, d: Object { e: 1, f: 2, g: true, h: Object { i: "hello" } }, j: Array [1, 2, 3], k: Array ["foo", "bar"], l: Array ["foo", 1, true], m: Array [Object { n: 10, o: "food", p: true }, Object { n: 11, o: "foog", p: true }], q: null, r: undefined } // Object { a: "", b: 0, c: undefined, d: Object { e: 0, f: 0, g: undefined, h: Object { i: "" } }, j: Array [0, 0, 0], k: Array ["", ""], l: Array ["", 0, undefined], m: Array [Object { n: 0, o: "", p: undefined }, Object { n: 0, o: "", p: undefined }], q: null, r: undefined }

提交回复
热议问题