Adding nested map values to firestore

Viewed 138

I'm pretty new to javascript and also firestore. I'm trying to add some values to the database which are generated from an input form.

I have the following values taken from the form:

Ingredient: Corriander Measure: Cups Amount: 1

So I wanted to have the structure:

ingredients: {ingredient: {Corriander: {amount:1, type:'cups'}}}

However, when I try and use my variables:

ingredients: {ingredient: {ing: {amount:am, type:mea}}}

The amount and measure values work fine, but the ingredient value enters into the database as "ing" and not the value "Corriander".

Here is my javascript:


    const generateTemplate = (ing, am, mea) => {
  const html = `

    <li class="list-group-item"><span>${am} </span><span>${mea}</span> of <span>${ing}</span><i class="far fa-trash-alt delete"></i></li>

  `;
  list.innerHTML += html;


 // console.log(ing);
  const newIng = {
    //user: userID,
    //name: recipeName,
    ingredients: {ingredient: {ing: {amount:am, type:mea}}},
    //created_at: firebase.firestore.Timestamp.fromDate(now),
  };
console.log(newIng);

        db.collection("recipes")
 .add(newIng)
.then(() => {
  console.log("ing added");
})
.catch((err) => {
  console.log(err);
});

};
2 Answers

You were looking for computed property names in Javascript objects. That allows you to put an expression in brackets [], that will be computed and used as the property name.

const propertyName = "name"

const myObj = {}
myObj[propertyName] = "Username"

console.log(myObject)
// {name: "Username"}
Related