Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
208 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...