JS3
JS3

Reputation: 1829

How can I display the data with a true inside the object?

Getting the users collection from firestore:

 useEffect(() => {
        if (currentUser) {
          const unsubscribe = db
            .collection("users")
            .doc(uid)
            .onSnapshot((snapshot) => {
          const arr = [];
          arr.push({
            ...snapshot.data(),
          });

          setUsers(arr);
          console.log(JSON.stringify(arr));
        });

      return () => {
        unsubscribe();
      };
    }
  }, [currentUser]);

This is what is shows where I console.log(JSON.stringify(arr));

[
  {
    1: { others: "books", items: { Item1: true, Item2: true } },
    2: {
      items: { Item3: true, Item2: true },
      others: "books",
    },

    displayName: Inigi,
    address: "US",
  },
];

How can I display those items like this?

These are the codes but I have this error:

 {user["1"]?.items.map((index) => (
              <li>{index.Item1}</li>
            ))}

the error:

TypeError: _user$.items.map is not a function

and with these codes, there's no error but it does not display anything:

{user["1"]?.items?.map?.((index) => (                   
     <li>{index.Item1}</li>                 
 ))}

Upvotes: 1

Views: 52

Answers (2)

Abbasihsn
Abbasihsn

Reputation: 2171

lets consider you have below data:

onst data = [
  {
    1: { others: "books", items: { Item1: true, Item2: true } },
    2: {
      items: { Item3: true, Item2: true },
      others: "books",
    },

    displayName: Inigi,
    address: "US",
  },
];

you can access each user as follow:

const user1 = x[0][1];
const userItems1 = x[0][1].items;

and then you can loop through its items and use them, for example I have made an array of this data:

let ar=[];
for (const [key, value] of Object.entries(userItems1)) {
  ar.push(value);
  console.log(`${key}: ${value}`);
}

then you can map this array to any components like li.

Upvotes: 1

Eyal Delarea
Eyal Delarea

Reputation: 141

Map is an Array function and the type of your data is an object.

typeof user["1"]?.items == object

which means you have to iterate the object with for..in or any way you'd like.

Example:

 const firestoreResponse = [
    {
        1: { others: "books", items: { Item1: true, Item2: true } },
        2: {
          items: { Item3: true, Item2: true },
          others: "books",
        },
    
        displayName: '',
        address: "US",
      },
 ]

//Destructure relevant data
const obejctItems = firestoreResponse[0][1].items
//Iterate the items object
for(let item in obejctItems){
    console.log(item)
}

output: Item1,Item2

Upvotes: 2

Related Questions