0

I understand that only array elements can be .push()'ed onto an array.

I want to accomplish the equivalent for an object.

I know the dot and bracket notation, so it's not that old question. I need to do it with variables in a loop.

I've looked into Object.assign() but can't seem to make that work.

Below function is called repeatedly. I need to normalize the data fed to the function into a mini database using a js object.

The last line is the crux. This will (of course) keep overwriting divContent[section].items[idValue].

How do I get it to "push" the record object into the key represented by items[idValue]?

I want to get { itemsKey: { k1:v1, k2:v2, k3:v3 } }. Thanks!

There is no need to maintain index order. The items need to be called later as itemsKey[k1] for example.

  function createItemDb (section, fileName, fileContent) {
    var fileExt = fileName.split('.')[1].toLowerCase();
    fileType = ((fileExt == 'caption') || (fileExt == 'url')) ? fileExt : 'img';
    if (fileType == 'img') {
      var regExp = /\((.*?)\)/g;
      var matches = regExp.exec(fileName);
      fileType = matches[1].toLowerCase();
    }
    var regRemoveParenIncl = /\([^)]*\)/;
    var regRemoveExt = /\.[^\/.]+$/;
    var idValue = fileName.replace(regRemoveParenIncl,'').replace(regRemoveExt,'');
    
    record = {};
    record[fileType] = fileName;
    
    divContent[section].items[idValue] = record;
  }
cjr
  • 25
  • 6
  • 2
    The thing that you say you "want to get" is not a valid JavaScript object. – Pointy Aug 01 '20 at 02:26
  • Please share an example of the expected result – Mario Aug 01 '20 at 02:46
  • Something like this, which SEEMS valid @Pointy - a key with nested key pairs - that's not an array, right? My original example was rushed and misleading, I will fix it. var myData = { "settings": { "displayAnnouncement": true, "fadeOutAnnouncement": true, "secondsUntilBeginFade": 5 } } – cjr Aug 01 '20 at 03:11

1 Answers1

-1

It seems you want a structure that can both:

  • Access by index (maintain order)
  • Access by key (unordered access)

This does not exist. What you can do is make a custom object that stores both an Array and an Object, and then make functions so you can both store and access with overridden parameters allowing both index (integer) and key (string).

Perhaps this can also help: Access non-numeric Object properties by index?

user
  • 675
  • 4
  • 11
  • [`The Map object holds key-value pairs and remembers the original insertion order of the keys.`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) – Hashbrown Aug 01 '20 at 03:13