Remove cleanObj

This commit is contained in:
Angelos Chalaris
2020-04-16 11:32:23 +03:00
parent 638e09d730
commit 007e9394e6
2 changed files with 0 additions and 36 deletions

View File

@ -1,27 +0,0 @@
---
title: cleanObj
tags: object,beginner
---
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 included in given array.
If you pass a special key,`childIndicator`, it will search deeply apply the 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;
};
```
```js
const testObj = { a: 1, b: 2, children: { a: 1, b: 2 } };
cleanObj(testObj, ['a'], 'children'); // { a: 1, children : { a: 1}}
```

View File

@ -1,9 +0,0 @@
const {cleanObj} = require('./_30s.js');
test('cleanObj is a Function', () => {
expect(cleanObj).toBeInstanceOf(Function);
});
const testObj = { a: 1, b: 2, children: { a: 1, b: 2 } };
test('Removes any properties except the ones specified from a JSON object', () => {
expect(cleanObj(testObj, ['a'], 'children')).toEqual({ a: 1, children: { a: 1 } });
});