Files
30-seconds-of-code/snippets/cleanObj.md
Angelos Chalaris b74eb9d9bd Linting
2017-12-27 11:02:46 +02:00

24 lines
749 B
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

### cleanObj
Removes any properties except the ones specified from a JSON object.
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];
}
 });
return obj;
};
/*
const testObj = {a: 1, b: 2, children: {a: 1, b: 2}}
cleanObj(testObj, ["a"],"children") // { a: 1, children : { a: 1}}
*/
```