JS3
JS3

Reputation: 1829

How do I convert the firestore data to a JSON object?

I have these codes:

const App = () => {
  const [users, setUsers] = useState();

  const getData = async () => {
    const citiesRef = firestore.collection("users");
    const snapshot = await citiesRef
      .where("item.itemName", "==", true)
      .where("item", "==", false)
      .get();
    if (snapshot.empty) {
      console.log("No matching documents.");
      return;
    }

    snapshot.forEach((doc) => {
      console.log(doc.data());
    });
  };

  useEffect(() => {
    getData();
  });

  return <div>Month</div>;
};

export default App;

If I'll console.log(doc.data()) this is what is shows: enter image description here

How can I convert this into a JSON object?

I wanted to have a JSON object in order to filter the data. Thank you.

Upvotes: 1

Views: 949

Answers (1)

Dharmaraj
Dharmaraj

Reputation: 50840

If you are trying to get an array of objects containing all documents' data to filter them, try this:

const usersData = snapshot.docs.map(d => ({id: d.id, ...d.data()}))
// set this array in your state
setUsers(usersData)

This will be an array and you can use methods like filter(), find() as required. For example, to get users having admin role in their roles array:

const admins = usersData.filter(user => user.roles.includes("admin"))

Upvotes: 1

Related Questions