我有这个对象
{
helloWorld: function () {
console.log("Test")
},
debug: false,
foo: {
test: "test",
bar: function () {
console.log(false)
}
}
}
但是,以编程方式我希望它看起来像这样:
{
helloWorld: function() {
console.log("Test")
},
foo: {
bar: function() {
console.log(false)
}
}
}
基本上删除除对象功能以外的所有内容。
最佳答案
您可以进行递归调用。对于对象的每个键值对,检查值:
- 如果是功能,就保留它
- 否则对该值进行递归调用
递归调用的基本条件
- 如果不是对象,返回null
- 如果对象为空,也返回null
在 map
通过键值对后,过滤 value
不等于 null 的对。
最后,将对转换回对象
function keepFunc(obj) {
if (!isObject(obj)) {
return null
}
if (Object.keys(obj).length === 0) {
return null
}
return Object.fromEntries(
Object.entries(obj)
.map(([key, value]) => [
key,
isFunction(value) ? value : keepFunc(value)
])
.filter(([key, value]) => value !== null)
)
}
可运行示例
const obj = {
helloWorld: function() {
console.log('Test')
},
debug: false,
moreDebug: {},
foo: {
test: 'test',
bar: function() {
console.log(false)
},
moreTest: {
weather: 'cool',
say: function () {
console.log('phew')
}
}
}
}
const isObject = obj => typeof obj === 'object' && obj !== null
const isFunction = func => typeof func === 'function'
function keepFunc(obj) {
if (!isObject(obj)) {
return null
}
if (Object.keys(obj).length === 0) {
return null
}
return Object.fromEntries(
Object.entries(obj)
.map(([key, value]) => [
key,
isFunction(value) ? value : keepFunc(value)
])
.filter(([key, value]) => value !== null)
)
}
console.log(keepFunc(obj))
引用资料
Object.entries() : 将对象转换为键值对
Object.fromEntries() : 将键值对转换为对象
关于javascript - 过滤除函数之外的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64148661/