Home > Software design >  Javascript reference nested object elements from another module
Javascript reference nested object elements from another module

Time:09-03

Simple question, but it doesn't seem to be working how I expect... I'm trying to access the value from a nested object, however I'm getting that (for this example) 'person' is not defined.

What am I doing wrong?

Example:

config.settings.js:

var configs = {
    person: {
        'name': 'John',
        'number': 27,
        'color': blue
    },
    place: {
        'town': 'springville',
        'population': 201827
    }
}
module.exports = configs;

main.js:

var configSettings = require('config.settings');
module.exports = {
    run: function(){
        console.log(configSettings[person][name]);
   }
}

CodePudding user response:

You have to use dot accessor such as

configSettings.person.name

And make sure your are properly importing your config.

CodePudding user response:

First make sure blue is defined otherwise is a typo and should be a string

person: {
        'name': 'John',
        'number': 27,
        'color': "blue"
    },

and I sugest use dot notation

configSettings.person.name

CodePudding user response:

Had to make the inner keys strings and reference with configSettings.person['name']

otherwise was getting type error.

  • Related