Add property to object when it's not null

不问归期 提交于 2020-03-13 06:06:09

问题


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?


回答1:


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

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

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

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



回答2:


Depending on the JS version you are using, you can use the spread operator ...

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 },
});


来源:https://stackoverflow.com/questions/40652364/add-property-to-object-when-its-not-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!