Issue
I have the following generic function written in TypeScript, should apply a patch to an object where the patch is a partial object of the same type:
function applyPatch<T extends object>(obj: T, patch: Readonly<Partial<T>>): T {
const patched = { ...obj, ...patch };
console.log(`obj: ${JSON.stringify(obj)}`);
console.log(`patch: ${JSON.stringify(patch)}`);
console.log(`patched: ${JSON.stringify(patched)}`);
return patched;
}
This should be easy enough. I tested the function in the typescript playground and it definitely works as expected.
I am running that function with cloudflare wrangler pages for local development at the time, and it seems to work for almost all cases, except for the case where the patch object is an empty object {}.
I have tried everything for quite some time now, but I cannot possible understand how this output happened:
obj: {"id":"test","data":"testdata"}
patch: {}
patched: {"id":"test"}
What is going on here? How is it possible that the data property just disappeared?
I was definitely expecting the data property to be set when running this.
Solution
I don't know where your patch object comes from or how it's created, but I see only one way how this could happen, ie if your patch is not {} but { testdata: undefined }. JSON.stringify will not serialize the undefined property, so it seems it vanished
let obj = {"id": "foo", "testdata": "bar" }
let patch = { "testdata": undefined }
let patched = {...obj, ...patch}
console.log("obj", obj);
console.log("obj", JSON.stringify(obj));
console.log("patch", patch);
console.log("patch", JSON.stringify(patch));
console.log("patched", patched);
console.log("patched", JSON.stringify(patched));
Depending on what you expect to happen in such a case, you could for instance remove the undefined values from the patch object.
let obj = {"id": "foo", "testdata": "bar" }
let patch = { "testdata": undefined }
for (let k in patch) {
if (patch[k] === undefined) delete patch[k];
}
let patched = {...obj, ...patch}
console.log("obj", obj);
console.log("obj", JSON.stringify(obj));
console.log("patch", patch);
console.log("patch", JSON.stringify(patch));
console.log("patched", patched);
console.log("patched", JSON.stringify(patched));
Answered By - derpirscher
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.