dragi
dragi

Reputation: 1512

How to get data out of object in React

I have an app that I built with React and Firebase and I just made a search component.

So in that I'll get the posts from the database and putting all of them into an array that is stored as a state. Then, I'm using that state with the search component (which is from Semantic UI React). It works, it searches the array and returns the results based on the "createdBy" field but when I try to get only the fields from it, it doesn't display anything anymore.

How can I only get the 'message' and 'createdBy' fields displayed? Or is there like a better process for search components if the database is in firebase?

state

As you can see I have the results inside the state there and I can display these results with JSON stringify but when I try to use 'results.message' for example, it doesn't work.

Can I get some help please? Thanks

Upvotes: 4

Views: 31209

Answers (1)

Hemadri Dasari
Hemadri Dasari

Reputation: 34014

Since results is an array you need to do .map or .forEach on it to access each object and it’s keys and values

  results.map( result => {
       console.log(result.message);
       console.log(result.uid);
       console.log(result.createdBy);
  }

Or using .forEach

  results.forEach( result => {
       console.log(result.message);
       console.log(result.uid);
       console.log(result.createdBy);
  }

If you want to access only first object from the array then

  console.log(results[0].message);
  console.log(results[0].uid);
  console.log(results[0].createdBy);

Upvotes: 4

Related Questions