0

I'm struggling to figure out how to compleate one simple piece of code I need for my project.

And my problem is that I need to create a key with ever increasing index inside of dataStorage array. Everytime the function run gets executed, I need to create a new key-value (again, inside dataStorage).

key0, key1, key2 and so on... A static value with just a changing number

Basically: I need the key value with the keyIndex increased by one: "key(keyIndex)", everytimethe the function is executed.

Is there a way to achieve this? If yes, then what should I do, and how about browser compatibility? I know from my pathetic experience that such things tend to need some tweaking in different browsers.

(Sorry if the question is confusing, I just don't know where to start with it...)

var keyIndex = 0;
var dataStorage = {
  key0: ['some data', 'some more data']
}

function run() {
  // some useless code
  
  // Increasing keyIndex by one.
  keyIndex++;
  
  // And here is the problem:
  dataStorage.key1 = 'some value';
  console.log(JSON.stringify(dataStorage)+'\nKeyIndex: '+keyIndex);
}

window.setInterval(run, 1000);

2 Answers2

1

You can use bracket notation instead of dot notation to add/access keys using variables:

var keyIndex = 0;
var dataStorage = {
  key0: ['some data', 'some more data']
}

function run() {
  keyIndex++;
  
  dataStorage['key' + keyIndex] = 'some value';
  console.log(JSON.stringify(dataStorage)+'\nKeyIndex: '+keyIndex);
}

window.setInterval(run, 1000);
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
0

We can start of with a key0 if dataStorage is empty, else we can extract the last key in the dataStorage object and add a new key by incrementing the number at the end.

This way we don't need to maintain an extra variable keyIndex polluting the global namespace:

let dataStorage = {};

function run() {
  const len = Object.keys(dataStorage).length - 1;
  let newKey = "";
  if(len >= 0) {
    newKey = "key" + (+Object.keys(dataStorage)[len].split("key")[1] + 1);
  }else{
    newKey = "key0";
  }
  dataStorage = {...dataStorage, [newKey] : "some value"};
  console.log(JSON.stringify(dataStorage));
}

run();
run();
run();
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44