deeveeABC
deeveeABC

Reputation: 986

How to iterate through an array inside an object?

I have a config.json file:

{
  "test": {
    "maths": [
      "core",
      "core2"
    ]
  }
}

In my index.js, I want to access the object 'test', and iterate through each of the maths elements.

I am new to arrays, so still trying to figure out how they work. What is wrong with this approach? (I know it does not work)

var CONFIG = require('./config.json')

var fn = CONFIG.test.maths

fn.forEach(function(value){
console.log(value);
});

Also, what is the correct way of doing this?

Upvotes: 2

Views: 679

Answers (4)

Anton Pudikov
Anton Pudikov

Reputation: 281

Try changing config.js to

module.exports = {
  "test": {
    "maths": [
      "core",
      "core2"
    ]
  }
};

As it stands now - your module doesn't export anything.

Update: if you prefer .json - this method won't work as .json can't be exported (but it can be required in node, see How to parse JSON using Node.js?), it works with .js files as modules. And you'll have to change this part too:

require('./config.js') 

Update2: it works as is with index.js

var CONFIG = require('./config')

var fn = CONFIG.test.maths

fn.forEach(function(value){
console.log(value);
});

config.json

{
  "test": {
    "maths": [
      "core",
      "core2"
    ]
  }
}

in my node v5.3.0

Upvotes: 2

Prakash Thiru
Prakash Thiru

Reputation: 41

You can simply use the JQuery method getJSON to load the Json into Javascript.

`$.getJSON( "config.json", function( data ) {
   console.log(data);
   var val = data.test.maths
   val.forEach(function (d) {
     console.log(d);
   })
 });`

Upvotes: 0

Marco Scabbiolo
Marco Scabbiolo

Reputation: 7449

3 posible solutions, choose the one that suits you the most:

  1. Change the file extension of config.js , to config.json
  2. Read the file instead and parse it as JSON: var CONFIG = JSON.parse(require('fs').readFile('./config.js'));

  3. Make the file a module that exports the JSON instead of plain JSON, as Anton suggested

Upvotes: 0

Greg Rebisz
Greg Rebisz

Reputation: 156

To fix this rename your config.js file to config.json (For naming convention sake)

Change:

var CONFIG = require('./config')

To:

var CONFIG = require('./config.json')

The reason is that requiring a file requires the exact filename including the extension

Upvotes: 0

Related Questions