不为null时向对象添加属性 [英] Add property to object when it's not null

查看:57
本文介绍了不为null时向对象添加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个小型API,我想使用HTTP PATCH REQUEST更新数据而不使用一堆if语句.我正在尝试仅使用更改后的数据填充传出数据对象.

I'm working on a small API and I want to update the data using HTTP PATCH REQUEST without using a bunch of if statements. I'm trying to fill the outgoing data object with the changed data only.

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?

推荐答案

您可以将Object.assign与三元运算符结合使用:

You could use Object.assign in combination with the ternary operator:

let data = Object.assign({},
  first === null ? null : {first},
  ...
);

之所以可行,是因为Object.assign会跳过null参数.

This works because Object.assign will skip over null parameters.

如果您确定该属性值不会是"falsy",那么编写该代码会短一些:

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,
  ...
}

这篇关于不为null时向对象添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆