Home > OS >  How can i get the elements from an array inside of json in firebase?
How can i get the elements from an array inside of json in firebase?

Time:05-28

i have this structure, in it there is an json object and that object have an array of json objects

i need to ask to them if color1 is red for example btw

name:carla
data: {
   sign: "carly",
   tools: [{trait:color1, value:red}, {trait:color2, value:white}] }
},
name:dany
data: {
   sign: "dan",
   tools: [{trait:color1, value:blue}, {trait:color2, value:black}] 
}

so i want to get only the elements have color1 red, in this case only should i get first one element

i tried with this

query = query.where('data.tools', "array-contains", {trait: 'color1', value: 'red'})

CodePudding user response:

Your query fetches documents where data.tools contains that object. It does not filter that array. You'll need to parse that object yourself after fetching the docs:

const qSnap = await query.get();

qSnap.docs.forEach((doc) => {
  const item = doc.data().data.tools.find(t => t.trait === 'color1' && t.value == 'red');
  console.log(item)
})

If you are trying to find a specific tool in a document, then you can create a sub-collection for tools. That way, you can query for one specific and also update it directly if required.

  • Related