typescript 当对象不为空时将属性添加到对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40652364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add property to object when it's not null
提问by Dawid Zbiński
I'm working on a small API and I want to update the data using HTTP PATCH REQUESTwithout using a bunch of if statements. I'm trying to fill the outgoing data object with the changed data only.
我正在开发一个小型 API,我想在HTTP PATCH REQUEST不使用一堆 if 语句的情况下更新数据。我正在尝试仅使用更改后的数据填充传出数据对象。
update() {
let prop1 = hasBeenChanged.prop1 ? changedData.prop1 : null;
// ...
let propN = hasBeenChanged.propN ? changedData.propN : null;
let data: ISomething = {
// something like --> property != null ? property: property.value : nothing
}
}
Is there any way to create the data object dynamically?
有没有办法动态创建数据对象?
回答by
You could use Object.assignin combination with the ternary operator:
您可以Object.assign与三元运算符结合使用:
let data = Object.assign({},
first === null ? null : {first},
...
);
This works because Object.assignwill skip over nullparameters.
这是有效的,因为Object.assign会跳过null参数。
If you are sure that the property value is not going to be "falsy", then it would be bit shorter to write:
如果您确定属性值不会是“假的”,那么编写会更短一些:
let data = Object.assign({},
first && {first},
...
);
Assuming the object is going to be stringified at some point, since stringification ignores undefined values, you could also try
假设对象将在某个时候被字符串化,因为字符串化会忽略未定义的值,您也可以尝试
let data = {
first: first === null ? undefined : first,
...
}
回答by Jason Carmona
Depending on the JS version you are using, you can use the spread operator ...
根据您使用的 JS 版本,您可以使用扩展运算符 ...
const getData = data => ({
...data.first && { 'Custom First Prop Name': data.first },
...data.second && { 'Custom Second Prop Name': data.second },
...data.third && { third: data.third },
...data.fourth && { fourth: data.fourth },
});

