'How to update only matching subset of object properties in TypeScript?
Let's say I have two types that share some properties:
type A = {
shared1: string;
shared2: string;
notShared1: string;
};
type B = {
shared1: string;
shared2: string;
notShared2: string;
};
Now, I just want to update the matching subset of properties for two of these objects:
class MyClass {
private const a = {
shared1: "s1",
shared2: "s2",
notShared1: "ns1"
};
// how can I achieve something like this:
private const b = { ...a, notShared2: "ns2" } // but without the 'notShared1' property of a
}
My idea
I tried to .filter
the first object by the matching keys but unfortunately the method itself doens't work:
private updateB() {
this.b = { ...this.a.filter(Object.keys(b)) } // filter method not available, why?
// (the filter content is not correct, just for better understanding what I try to achieve here)
}
Solution 1:[1]
This is something you can do in JavaScript. Given your definitions of a and b, runtime objects can be updated like:
a = { shared1: "s1", shared2: "s2", notShared1: "ns1" };
b = { shared1: "not s1", shared2: "not s2", notShared2: "ns2" };
for (const key in a) {
if (b.hasOwnProperty(key)) {
b[key] = a[key];
}
}
console.log(b);
// output: Object { shared1: "s1", shared2: "s2", notShared2: "" }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Suncat2000 |