I want to filter of my snapshot but i sometimes i am getting [undefined], i dont want to return undefined inside, what is the issue?
return snapshot.docs.map((doc) => {
const jn = JSON.parse(doc.data().jsonData)
const res= jn.attributes.find(t => t.typet === tokenAttrs[0].name);
if(res){
return doc.data()
}
})
CodePudding user response:
May it can't find the attribute that match the condition,cause the res
is undefined. You should check it out.
CodePudding user response:
You can use the filter
function this way:
return snapshot.docs.map(doc => {
const jn = JSON.parse(doc.data().jsonData);
const res = jn.attributes.find(t => t.typet === tokenAttrs[0].name);
if (res) return doc.data();
}).filter(_ => _ !== undefined);
This will remove the undefined
values from the array.
CodePudding user response:
Many ways to solve it. One would be to use a foreach and push the new value to an new array. or you filter the empty values from your result before you send it back. like that:
const r = snapshot.docs.map((doc) => {
const jn = JSON.parse(doc.data().jsonData)
const res= jn.attributes.find(t => t.typet === tokenAttrs[0].name);
if(res){
return doc.data()
} else {
return null;
}
})
// then remove all empty values
return r.filter(n => n)
with forEach()
const res = [];
snapshot.docs.forEach((doc) => {
const jn = JSON.parse(doc.data().jsonData)
const res= jn.attributes.find(t => t.typet === tokenAttrs[0].name);
if (res){
res.push(doc.data());
}
})
return res;
CodePudding user response:
Array.prototype.find
will search through the array and gets all the match data. If nothing is found, it returns undefined
. You just need to create a logical OR
expression. See code below:
return snapshot.docs.map((doc) => {
const jn = JSON.parse(doc.data().jsonData)
// will now return null if there's no matched data.
const res = jn.attributes.find(t => t.typet === tokenAttrs[0].name) || null;
if(res){
// this will not return if `res` is null
return doc.data()
} else {
// you could do `else` here if you want to do something if there's no matched data.
// Do something
}
})