I'm having some difficulty trying to write a function that takes two inputs:
- The name of an object
- The name of a property
and prints the value of that property for that object. However, the objects all have different properties, they're not all the same.
The objects look like this:
class object1 {
get property1() {
return 'foo';
}
get property2() {
return 'bar';
}
}
export default new object1();
class object2 {
get different1() {
return 'asdf';
}
get different2() {
return 'ghjk';
}
}
export default new object2();
Here's what I'm tried so far:
import object1 from '..';
import object2 from '..';
getPropertValue(objectName, propertyName) {
let objects = [object1, object2];
let index = objects.indexOf(objectName);
console.log(objects[index][propertyName]);
}
This didn't work, came back as undefined. It seems like index is being calculated correctly, but it doesn't seem like objects[index][propertyName] is properly accessing the object's value. Though weirdly, when I tried the following, it ALMOST worked:
import object1 from '..';
import object2 from '..';
getPropertValue(objectName, propertyName) {
let objects = [object1, object2];
for (let index in objects) {
console.log(objects[index][propertyName]);
}
}
Here I actually got it to print the correct value, but the problem is that since I'm just iterating over all the objects in a for loop, it tries to print the value for all objects, instead of just the one that matches the objectName. So it prints the correct value for the object that has the property I'm trying to access, but then gets undefined for the other object which does not have that property.
I suppose I could add some property to each object called name and do something like this:
getPropertValue(objectName, propertyName) {
let objects = [object1, object2];
for (let index in objects) {
if(objects[index].name == objectName) {
console.log(objects[index][propertyName]);
}
}
}
But I'd rather not add unnecessary properties to these objects if I can help it.
Is there a better way to do this?
objectName? What does "the name of an object" mean to you exactly? Objects can be referenced by a variable name (which you cannot reference dynamically), but the object itself has no quality of being "named" unless you explicitly make that part of your data model.objectNameisobject1orobject2.