从打字稿中的对象中删除null属性
作为参考从javascript中的对象中删除空白属性,如何使IT typescript兼容?
JS函数(嵌套对象| ES10 ):
function removeEmpty(obj) {
return Object.fromEntries(
Object.entries(obj)
.filter(([_, v]) => v != null)
.map(([k, v]) => [k, v === Object(v) ? removeEmpty(v) : v])
);
}
我尝试了dubl< t,null>
,但它与嵌套对象无效,我认为这不是正确的使用的实用程序。
请注意,返回的类型应删除null
类型,但要保留undefined
。
示例/预期行为:
type TestType = {
a?: {
b?: {
c: string;
} | null;
z?: {
x: string;
};
} | null;
};
const testObj: TestType = {
a: {
b: null,
z: { x: 'Hi' }
}
};
const resultObj = removeEmpty(testObj);
其中resultobj
类型类似于:
type ResultTestTypeExample = {
a?: {
b?: {
c: string;
};
z?: {
x: string;
};
};
};
As reference Remove blank attributes from an Object in Javascript, how to make it Typescript compatible?
JS function (nested objects | ES10):
function removeEmpty(obj) {
return Object.fromEntries(
Object.entries(obj)
.filter(([_, v]) => v != null)
.map(([k, v]) => [k, v === Object(v) ? removeEmpty(v) : v])
);
}
I've tried with Exclude<T, null>
but it doesn't works with nested objects and I think it's not the correct utility to use.
Note that the returned type should remove null
type(s) but keeps undefined
.
Example/Expected behaviour:
type TestType = {
a?: {
b?: {
c: string;
} | null;
z?: {
x: string;
};
} | null;
};
const testObj: TestType = {
a: {
b: null,
z: { x: 'Hi' }
}
};
const resultObj = removeEmpty(testObj);
Where resultObj
type is similar to:
type ResultTestTypeExample = {
a?: {
b?: {
c: string;
};
z?: {
x: string;
};
};
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这个适合您吗?
Usage:
Playground
Does this work for you?
Usage:
Playground
您可以使用上面的代码删除
null
元素。您还可以给您的类型,它将删除所有嵌套对象属性You can remove
null
elements with the code above. You can also give your type and it will remove all nested objects properties