DORRITO
DORRITO

Reputation: 661

Call Object based off of string

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

Answers (3)

Shubham Khatri
Shubham Khatri

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

keul
keul

Reputation: 7819

Convert res.catName.name to res[catName].name

Upvotes: 1

user2652134
user2652134

Reputation:

You need array notation for that.

res[catName].name

Upvotes: 1

Related Questions