I'm setting up an object with year objects, month arrays, and days that are arrays of post objects. When I try to push data to postData[year][month][date]
, it pushes to all the date arrays in month
.
let postData = {}
const addPosts = (year, month, newPosts) => {
postData[year] = postData[year] || {}
postData[year][month] = postData[year][month] || Array(30).fill([])
postData[year][month][0].push('post')
return postData
}
Outputs:
{
"2020": {
"4": [
[
"post"
],
[
"post"
],
[
"post"
],
...
]
}
}
Is there something about .push() I'm not understanding or is there a limit to the number of indexes you can .push() into?
This issue happens because you have assigned the same empty array []
as a reference to all of them like Array(30).fill([])
. So, when you modify any one of them, it also updates each one of them like:
const arr = Array(2).fill([])
arr[0].push('post')
console.log(arr) //=> [["post"], ["post"]]
In this demo, you can't see this properly but if you open chrome console then you can see the actual result.
To fix this issue you can simply use .map()
method and assign a new array []
to each item in the main array like:
const arr = Array(2).fill().map(a => []);
arr[0].push('post')
console.log(arr) //=> [["post"], []]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With