Home > front end >  How can I make my array into a map when saved in Firestore?
How can I make my array into a map when saved in Firestore?

Time:02-10

I have dynamic text fields that would repeat every time I'll click a button. As of now, the colorList is an array, and this is how it shows in the console I plan to save this in firestore.

console

enter image description here

Firebase

I wanted to store this in Firebase as map so it'll be something like red: 10 since I would be updating these stocks red

enter image description here

Codes

const [colorList, setColorList] = useState([{ color: "", colorStocks: "" }]);


{colorList.map((singleColor, index) => (
        <div key={index}>
          <div style={{ display: "flex" }}>
            <Grid item>
              <TextField
                label="color"
                name="color"
                type="text"
                id="color"
                required
                value={singleColor.color}
                onChange={(e) => handleColorChange(e, index)}
              />
            </Grid>
            <br />
            <Grid item >
              <TextField
                label="Stocks"
                name="colorStocks"
                type="number"
                id="colorStocks"
                required
                value={singleColor.colorStocks}
                onChange={(e) => handleColorChange(e, index)}
              />
            </Grid>
          </div>
          <br />
           //buttons here to add and remove textfields
        </div>
      ))}

CodePudding user response:

You can use Array.prototype.reduce() for this:

const colorMap = colorList.reduce(function(map, obj) {
   map[obj.color] = obj.colorStocks;
   return map;
}, {});
  •  Tags:  
  • Related