Reputation: 661
I am trying to call an object from my node backend through react, but I am trying to do so based off of a string. So if the string is 'Cat', I am wanting to access the Cat
object and any other key/values under it.
Example of what the code looks like:
componentDidMount() {
let catName = 'Cat' //this string is actually passed in
this.callApi()
.then(res => this.setState({ catsName: res.catName.name }))
//catsName: res.Cat.name works
.catch(err => console.log(err));
}
callApi = async () => {
//lets say this example route has all animals in the world as objects
const response = await fetch('/animals');
const body = await response.json();
if (response.status !== 200) throw Error(body.message);
return body;
};
I know that it isn't working because it's a string, but trying to convert both the string or the object hasn't been working either. I'm limited in my node knowledge, any advice or clues? Or is this not even possible and I'm calling it wrong? Thanks ahead of time.
Example of what the node backend looks like for this example if helps. All animals would have key values in their api files (name, age, herbivore, etc..):
app.get('/animals', (req, res) => {
res.send({ Cat, Dog, Cougar, Wolf, etc.... });
});
Upvotes: 0
Views: 41
Reputation: 281864
You need to use the brackets syntax when you want to access a dynamic keys within an object.
catsName: res[catName].name
Check this documentation of Property accessors
Upvotes: 1