Reputation: 3299
I'm trying to create an empty object, then add properties to this object x number of times within a loop.
I want each property key to be assigned a name based on the loop integer.
I'm always left with only the last value... Plus it seems to be assigning the property key to the name of the variable, rather than the name I'm giving it. I've tried multiple iterations of setState, each with the same result:
const [vgJson, setVgJson] = useState({});
for (let i=1; i <= 300; i++) {
let key = "1234567" + i;
let newItem = {};
newItem[key] = {
"createdDate":"2021-08-15T22:34:28.000",
"id":key
}
let addVg = newItem[key];
setVgJson({...vgJson, addVg});
}
I've tried other methods such as:
setVgJson((prevState) => ({
...prevState,
addVg
}));
Gives the same result...
My goal is to return an object that looks like this:
{
"12345671":{"id":"12345671", "createdDate":"2021-08-15T22:35:28.000" },
"12345672":{"id":"12345672", "createdDate":"2021-08-15T22:35:28.000" }
}
// All the way to 300....
I keep ending up with this (from console.log):
{addVg: {…}}
addVg:
createdDate: "2021-08-15T22:34:28.000"
id: "1234567300"
[[Prototype]]: Object
I don't want the key to be addVg. I want it to be the value of the key
variable.
It keeps just giving me the last property I created in the loop. What am I doing wrong?
Upvotes: 0
Views: 130
Reputation: 562
Try This
const [vgJson, setVgJson] = useState({});
for (let i=1; i <= 300; i++) {
let key = "1234567" + i;
setVgJson({...vgJson ,
[key]:{"createdDate":"2021-08-15T22:34:28.000",
"id":key}
})
}
Upvotes: 0
Reputation: 3299
Don't know what I was thinking, as I'm very familiar with this behavior. This is what comes from switching technologies for a few months.
Anyways, declaring an object and setting state outside the loop fixed this up:
useEffect(() => {
let vbObj = {};
for (let i=1; i <= 300; i++) {
let key = "1234567" + i;
let addVg = {
"createdDate":"2021-08-15T22:34:28.000",
"id":key
}
vbObj[key] = addVg;
}
setVgJson(vbObj);
}
Upvotes: 1
Reputation: 26
or u can simply create a copy of object and push the value and set value
for (let i = 1; i <= 300; i++) {
let key = "1234567" + i;
let temp = vgJson;
temp[key] = {
createdDate: "2021-08-15T22:34:28.000",
id: key
};
setVgJson(temp);
}
Upvotes: 0