Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.push() only to specific index of an object?

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?

like image 442
michaelpanik Avatar asked Oct 20 '25 08:10

michaelpanik


1 Answers

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"], []]
like image 178
palaѕн Avatar answered Oct 22 '25 21:10

palaѕн