Saturday, June 1, 2024
 Popular · Latest · Hot · Upcoming
174
rated 0 times [  175] [ 1]  / answers: 1 / hits: 53402  / 8 Years ago, mon, february 29, 2016, 12:00:00

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?


More From » object

 Answers
21

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.


[#63119] Friday, February 26, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ellisw

Total Points: 625
Total Questions: 92
Total Answers: 88

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
ellisw questions
Mon, Aug 23, 21, 00:00, 3 Years ago
Fri, Nov 20, 20, 00:00, 4 Years ago
Sat, Jun 20, 20, 00:00, 4 Years ago
Tue, Apr 21, 20, 00:00, 4 Years ago
;