简体   繁体   中英

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?

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"], []]

For reasons that I cannot explain, the answer was to forego push() , and instead set the value of that index to a new array:

let postData = {}

const addPosts = (year, month, newPosts) => {
  postData[year] = postData[year] || {}
  postData[year][month] = postData[year][month] || Array(30).fill([])
  postData[year][month][0] = [...postData[year][month][0], 'post']

  return postData
}

I'm going to leave this up for anyone in the future Googling for strange Array push behaviors in React, js.push() not working

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