diff --git a/snippets/clean-json-objects.md b/snippets/clean-json-objects.md new file mode 100644 index 000000000..5af7b6221 --- /dev/null +++ b/snippets/clean-json-objects.md @@ -0,0 +1,21 @@ +### Clean Json objects + +Use `Object.keys()` method to loop over given json object and deleting keys that are not `include`d in given array. +also if you give it a special key(`childIndicator`) it will search deeply inside it to apply function to inner objects too. + +```js +const cleanObj = (obj, keysToKeep = [], childIndicator) => { + Object.keys(obj).forEach(key => { + if (key === childIndicator) { + cleanObj(obj[key], keysToKeep, childIndicator) + } else if (!keysToKeep.includes(key)) { + delete obj[key] + } + }) +} +/* + testObj = {a: 1, b: 2, children: {a: 1, b: 2}} + cleanObj(testObj, ["a"],"children") + console.log(testObj)// { a: 1, children : { a: 1}} +*/ +```