Search code examples
javascriptnode.jsdata-structuresjavascript-objects

Creating an object key to field pair in NodeJS saying it's undefined


I am new to Javascript and I want to know why when I create the following object...

this.prospectCollection = {};

I can't add objects to it using (refer to line 14)

miningProspect(num,address)
  {
    console.log(`Checking for string: ${num}`);
    let odds;
    if(num == 0 || num == 0.00000000001 || num == 0.00000000005 || num == 0.00000000010)
    {
      if(address in this.prospectCollection)
      {

        this.prospectCollection[address][num] += 1;

        //calculate prospects here

      }
      else
      {
        this.prospectCollection[address][num] = 1;
      }

    }
    else
    {
      return false;
    }
    
    return true; 
    
  }

I thought to give the object dynamic names I use the bracket notation but it's giving me this error in the console...

this.prospectCollection[address][num] = 1;
                                              ^

TypeError: Cannot set property '0.00000000001' of undefined

Any help or insight will be greatly appreciated.

EDIT:

is it this.prospectCollection = {[address]:{[num]:1}}; ? Wouldn't that assign it to that though and not be able to .push() things like you would an array?


Solution

  • Essentially, the key part of your code can be rewritten like this:

    if(!(address in this.prospectCollection))
    {
      this.prospectCollection[address][num] = 1;
    }
    

    But that's not correct JS, as you're basically trying to access property of undefined (which is this.prospectCollection[address]). There's no autovivification in JS.

    One possible way is just creating an object if it's not there (manual vivification):

    this.prospectCollection[address] = this.prospectCollection[address] || {};
    this.prospectCollection[address][num] = (this.prospectCollection[address][num] || 0) + 1;
    

    Another viable option is using some library function that provides autovivification - such as lodash.set. It can be as concise as...

     const path = ['prospectCollection', address, num];
    _.set(this, path, _.get(this, path, 0) + 1);