user3480305
user3480305

Reputation:

How to push an objects into an array inside another root array

I am working with GPS related program so I am actively receiving many location objects. This is the array form I would want to achieve. Initially it should be an empty array and then start with only one child, all incoming location objects would be stored in that one child until some other command is issued. When next event starts, all incoming objects would be stored in second child array, hope you get the gists.

rootArray = [
  [
    {lat: '', long: ''},
    {lat: '', long: ''},
    {lat: '', long: ''},
  ],
  [
    {lat: '', long: ''},
    {lat: '', long: ''},
    {lat: '', long: ''},
  ]
]

This is what I have tried but did not succeed.

// I am working with redux here actually
// rootArray: []

case NEW_LOCATION_OBJECT_COMING:
  return {
    ...state,
    rootArray: state.rootArray[state.rootArray.length].concat(action.payload.locationObject),
  }

Upvotes: 0

Views: 311

Answers (1)

G4bri3l
G4bri3l

Reputation: 5146

The items in the array are indexed from 0 to length - 1, so if you try to access the element at index length you will get undefined. We should do this:

...
rootArray: [
  ...state.rootArray.slice(0, state.rootArray.length - 1),
  state.rootArray[state.rootArray.length - 1].concat(action.payload.locationObject)
],
...

The reason is that with the previous approach we were assigning to the rootArray the result of concatenating its last element with the payload, so everything else would get lost and our rootArray would become just a simple array of objects.

We need to preserve what we have by extending the existing array, to achieve this I create a new array that looks like the old rootArray without the last element, the new last element is then the concatenation of the old last element and the payload. I hope it makes sense.

EDIT Given your comment it depends on how you initiate your rootArray if it's just an empty array then this approach fails and instead you should do:

...
rootArray: [
  ...state.rootArray.slice(0, state.rootArray.length - 1),
  state.rootArray.length > 0
    ? state.rootArray[state.rootArray.length - 1].concat(action.payload.locationObject)
    : [...action.payload.locationObject]
],
...

Otherwise you can just initiate the rootArray to [[]] and use the the first version.

Upvotes: 2

Related Questions