Y.Futekov
Y.Futekov

Reputation: 544

How to change object keys on the fly?

Wall of text, please bear with me. I'm willing to provide all code needed to resolve the issue, but I don't know where to start so first there's explanation of the problem, and I will be very grateful if someone can help me out with this.

I'm using Vue/Vuex and a curious (a least to me) issue has arisen in my application: I have a an Array populated with Objects of documents that I fetch from MySQL DB, and every time the user selects one of them from a list, it's moved from the documents Array to the "Selected" Object of Objects, and it's assigned a unique key, that is the current route the user is at, and it looks like this:

/machines/1/home : { }

Then, he opens another tab, selects a document, etc. and now the "Selected" looks like this

{/machines/1/home : { }, /machines/2/home : { }, /machines/3/home : { }}

After all this, for each tab (identified by its current route), I'm displaying a unique document. When the user closes the last tab, the document and its key are removed successfully, but if he decides to close the second of three tabs, everything breaks because now I have tab 1 & tab 3 (with "Selected" being

{/machines/1/home : { }, /machines/3/home : { }}

but the routes of the tabs are

{/machines/1/home, /machines/2/home}

So in conclusion, what I'm asking is: Is it possible to change the remaining object keys in "Selected" to match the new tabs?

Upvotes: 0

Views: 137

Answers (1)

Ja9ad335h
Ja9ad335h

Reputation: 5075

You can use Array of Objects for selected and later create Object of Object when needed.

in Array, if you delete 2nd item, 3rd item will take 2nd item's place and so on..

for ex:

const selectedArray = [{
  val: 'one'
}, {
  val: 'two'
}, {
  val: 'three'
}];

// remove/close 2nd tab
let removedTab = 2;
selectedArray.splice(removedTab - 1, 1);

const selected = selectedArray.reduce((a, d, i) => {
  a[`/machines/${i + 1}/home`] = d;
  return a;
}, {});

console.log(selected)

Upvotes: 1

Related Questions