Last active
August 10, 2020 15:58
-
-
Save semihkeskindev/d979b169e4ee157503a76b06573ae868 to your computer and use it in GitHub Desktop.
Clear all values without delete properties in object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function clearAllValues(data, byTypeOf = false) { | |
let clearValuesTypeOf = { | |
boolean: false, | |
number: 0, | |
string: '', | |
} | |
// clear array if data is array | |
if (Array.isArray(data)) { | |
data = []; | |
} else if (typeof data === 'object' && data !== null) { | |
// loop object if data is object | |
Object.keys(data).forEach((key, index) => { | |
// clear array if property value is array | |
if (Array.isArray(data[key])) { | |
data[key] = []; | |
} else if (typeof data[key] === 'object' && data !== null) { | |
data[key] = this.clearAllValues(data[key], byTypeOf); | |
} else { | |
// clear value by typeof value if second parameter is true | |
if (byTypeOf) { | |
data[key] = clearValuesTypeOf[typeof data[key]]; | |
} else { | |
// value change as null if second parameter is false | |
data[key] = null; | |
} | |
} | |
}); | |
} else { | |
if (byTypeOf) { | |
data = clearValuesTypeOf[typeof data]; | |
} else { | |
data = null; | |
} | |
} | |
return data; | |
} | |
let object = { | |
name: 'Semih', | |
lastname: 'Keskin', | |
brothers: [ | |
{ | |
name: 'Melih Kayra', | |
age: 9, | |
} | |
], | |
sisters: [], | |
hobbies: { | |
cycling: true, | |
listeningMusic: true, | |
running: false, | |
} | |
} | |
console.log(object); | |
// output before changed: {"name":"Semih","lastname":"Keskin","brothers":[{"name":"Melih Kayra","age":9}],"sisters":[],"hobbies":{"cycling":true,"listeningMusic":true,"running":false}} | |
let clearObject = clearAllValues(object); | |
console.log(clearObject); | |
// output after changed: {"name":null,"lastname":null,"brothers":[],"sisters":[],"hobbies":{"cycling":null,"listeningMusic":null,"running":null}} | |
let clearObject2 = clearAllValues(object); | |
console.log(clearObject2); | |
// output after changed by typeof: {"name":"","lastname":"","brothers":[],"sisters":[],"hobbies":{"cycling":false,"listeningMusic":false,"running":false}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment