1

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)
shaedopotato
  • 457
  • 1
  • 3
  • 12

1 Answers1

1

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)
Spectric
  • 30,714
  • 6
  • 20
  • 43