简体   繁体   中英

How can I make my array into a map when saved in Firestore?

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

在此处输入图像描述

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

在此处输入图像描述

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>
      ))}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM