Reputation: 153
I'm trying to use variable as a firestore doc path :
console.log(change.doc.data().m_1.name); <----- This work well !
a = 1;
let me = change.doc.data().m_+a; <----- But not that....
console.log(me.name);
How can i do that ? Thank you in advance ! :)
Upvotes: 1
Views: 32
Reputation: 752
When you use your a
variable in your example you're asking JS to add the number 1 to your functions output. This is not the correct way. You want to use a key to access the data from your data()
functions return output as shown below.
change = {
doc: {
data: function() {
return {
m_1: {
name: "Mario",
occupation: "plumber",
siblings: 1,
age: 24
},
m_2: {
name: "Mike",
occupation: "developer",
siblings: 3,
age: "28"
}
}
}
}
}
console.log("Old way:" + change.doc.data().m_1.name);
const a = 1;
let me = change.doc.data()['m_' + a];
console.log("Desired way: " + me.name)
I have assumed a simple data structure derived from your question but I am not certain that it's what you get. But it might look a little like it.
EDIT awww.... The page didn't refresh and I did not see the two first answers :( well... at least we agree
Upvotes: 1
Reputation: 317750
I think you want to build the name of the key as its own variable and use that to index into the object.
const a = 1;
const key = "m_" + a;
const me = change.doc.data()[key];
Upvotes: 3
Reputation: 699
You should use brackets when using dynamic property.
let me = change.doc.data()['m_' + a];
Upvotes: 3