从 JSON 对象删除除了指定属性之外的任何其他属性。
使用 Object.keys()
方法遍历给定的 JSON 对象并删除不包含在给定数组中的 keys 。此外,如果你给它一个特殊的键(childIndicator
),它会深入地搜索内部对象应用该函数。
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}}
更多代码 JavaScript 实用代码片段 请查看 https://www.html.cn/30-seconds-of-code/
最新评论
写的挺好的
有没有兴趣翻译 impatient js? https://exploringjs.com/impatient-js/index.html
Flexbox playground is so great!
感谢总结。
awesome!
这个好像很早就看到类似的文章了
比其他的教程好太多了
柯理化讲的好模糊…没懂