In JavaScript, if I want to loop through a dictionary and set properties of another dictionary, I'd use something like this:
for (let key in dict) { if (obj.hasOwnProperty(key)) { obj[key] = dict[key]; } }
If obj
is a TypeScript object (instance of a class), is there a way to perform the same operation?
The hasOwnProperty() method returns true if the specified property is a direct property of the object — even if the value is null or undefined . The method returns false if the property is inherited, or has not been declared at all.
A good rule of thumb is that if you're looking to see whether an object has a property, you should use hasOwnProperty() . If you're looking to see if an object has a function that you intend to call, like checking if an object has toString() , you should use in .
The hasOwnProperty() method in JavaScript is used to check whether the object has the specified property as its own property. This is useful for checking if the object has inherited the property rather than being it's own. Syntax: object.hasOwnProperty( prop )
The hasOwnProperty() method returns true if the property is directly present in the object (not in its prototype chain). If an object is an Array, then the hasOwnProperty() method can check if an index is available (not empty) in the array.
If obj is a TypeScript object (instance of a class), is there a way to perform the same operation?
Your JavaScript is valid TypeScript (more). So you can use the same code as it is.
Here is an example:
class Foo{ foo = 123 } const dict = new Foo(); const obj = {} as Foo; for (let key in dict) { if (obj.hasOwnProperty(key)) { obj[key] = dict[key]; } }
Note: I would recommend Object.keys(obj).forEach(k=>
even for JavaScript, but that is not the question you are asking here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With