Search code examples
javascriptarraysobjectconcatenationpush

Pushing to an array inside an object references the pushed object


The snippet is detailing my problem. I have an object that stores an array of objects (some of which are arrays). When I push to these internal arrays, that value pushes to all of the elements in the array instead of just the index I'm looking for.

I feel like this should be a really easy fix - but I've tried everything. Switching to concat,push,putting things into for loops. When I run a simplified version in the snippet - (see snippet below) - then it says there's a "ref" to a certain ID. I'm not sure what this means, but my guess is that someone does know! any help would be great.

const runs = {
  AC: {
    L: Array(10).fill({
      stim: [],
      mask: [],
      resp: [],
      other: []
    }),
    R: Array(10).fill({
      stim: [],
      mask: [],
      resp: [],
      other: []
    })
  },
}

let runData = runs["AC"]["R"][3]

runData.stim.push(40)

console.log(runs.AC.R)


Solution

  • You are filling the array with the same reference. Instead, fill the array with empty items, then map to insert the object:

    runs = {
      AC: {
        L: Array(10).fill().map(e=>({
          stim: [],
          mask: [],
          resp: [],
          other: []
        })),
        R: Array(10).fill().map(e=>({
          stim: [],
          mask: [],
          resp: [],
          other: []
        }))
      },      
    }
    
    let runData = runs["AC"]["R"][3]
    
    runData.stim.push(40)
    
    console.log(runs.AC.R)