Reputation: 440
I have a typescript class with 2 private properties and an array of objects.
class AssigningProperties {
private animalType1: string;
private animalType2: string;
animals = [
{
name: "Bob",
type: "cat"
},
{
name: "Max",
type: "dog"
}
];
constructor() {
this.animals.forEach(v => console.log(v.name));
}
}
new AssigningProperties ();
I want to assign the class property animalType1
to cat
and animalType2
to dog
, preferably using Array.foreach
.
I can assign it using index of the objects like so:
this.animalType1 = this.animals[0].type;
but I feel there's a better approach. Help?
Upvotes: 2
Views: 1015
Reputation: 1075855
What you're doing is fine, but if you want to do it in a loop, make animalTypes
an array:
private animalTypes: string[];
Then you'd use the second parameter for the forEach
callback, which is the index of the entry:
this.animals.forEach((v, i) => v.type = this.animalTypes[i]);
Or if you meant that you wanted to assign "cat"
to the first animalTypes
(which is what your CodeSandbox code is doing), then:
this.animals.forEach((v, i) => this.animalTypes[i] = v.type);
With either of those, you'll end up with the type stored in two places, which creates a maintenance hazard — you can update animals[0].type
without updating animalType1
/animalTypes[0]
.
Assuming you wanted animals
to be the one source of truth, you might use getters instead:
private get animalType1(): string {
return this.animals[0].type;
}
private get animalType2(): string {
return this.animals[1].type;
}
Or for the animalTypes
approach, you'd use a Proxy:
interface Animal {
name: string;
type: string;
}
class AssigningProperties {
animals: Animal[] = [
{
name: "Bob",
type: "cat"
},
{
name: "Max",
type: "dog"
}
];
private animalTypes = new Proxy<Animal[]>(this.animals, {
get(target, propName) {
if (propName in target) {
return Reflect.get(target, propName).type;
}
return undefined;
}
});
}
Upvotes: 2