Skip to content

Instantly share code, notes, and snippets.

@buddypia
Created November 13, 2021 04:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save buddypia/5abff6998f8af4d8402b1425473f5964 to your computer and use it in GitHub Desktop.
Save buddypia/5abff6998f8af4d8402b1425473f5964 to your computer and use it in GitHub Desktop.
JSONのプロパティを再帰的にnullに初期化する関数
const json = JSON.parse('{"id":"vhUfi3t31goA","string":"root","number":1,"arrayString":["string1","string2"],"arrayNumber":[1,2],"object":{"childId":"boihF33gS3","childString":"child","childNumber":1,"childArrayString":["child_string1","child_string2"],"childArrayNumber":[1,2]}}');
SetNullRecursiveAllProperties(json);
function SetNullRecursiveAllProperties(obj) {
for (var property in obj) {
if (obj.hasOwnProperty(property) && typeof obj[property] === 'object') {
SetNullRecursiveAllProperties(obj[property]);
}
else if (obj.hasOwnProperty(property)) {
obj[property] = null;
}
}
}
console.log(json);
// > Object { id: null, string: null, number: null, arrayString: Array [null, null], arrayNumber: Array [null, null], object: Object { childId: null, childString: null, childNumber: null, childArrayString: Array [null, null], childArrayNumber: Array [null, null] } }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment