0

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>
      ))}
JS3
  • 1,623
  • 3
  • 23
  • 52
  • Does this [answer](https://stackoverflow.com/questions/26264956/convert-object-array-to-hash-map-indexed-by-an-attribute-value-of-the-object) your question? – Priyashree Bhadra Feb 10 '22 at 07:47

1 Answers1

1

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

const colorMap = colorList.reduce(function(map, obj) {
   map[obj.color] = obj.colorStocks;
   return map;
}, {});
asiralc
  • 36
  • 1
  • Thank you. Do I need to wrap this in `useEffect` or other methods since everytime I'll try to input in any field, `colorMap` will always render in the console in the background – JS3 Feb 10 '22 at 01:55
  • It depends. If you only want to save `colorMap` to firebase, than you can just convert `colorList` to map using that function just before updating the document. – asiralc Feb 10 '22 at 14:50