2

I am trying to loop over each entry in "default", in my JSON file below, within an EJS partial.

{
    "default": {
        "1": {
            "id": "alertmessages",
            "title": "Your Messages",
            "subtitle": "Tasks waiting for your attention",
            "image": "alert.png",
        },
        "2": {
            "id": "uploadr",
            "title": "Upload",
            "subtitle": "Upload",
            "image": "baskets.png",
        },
        etc............
    }
}

I am reading this JSON file into my node.js, parsing it and making it available for my dashboard view. as below

var jsondata = JSON.parse(require('fs').readFileSync('./app/routes/dashboard/buttons.json', 'utf8'));

var content = {
    title: 'Dashboard',
    user: req.user,
    buttonsdata: jsondata
};
res.render('dashboard', content);

My dashboard view, includes an ejs partial in which I am trying to loop over all the objects contained within default (this number may vary). I want to do this without Jquery. But having trouble getting any of the suggestions working that I have found on other threads.

console.log("<%= buttonsdata.default.[1].id %>")

gives me what I would expect, however if i try and console log buttons.length, which is used in loop examples I have seen, it just comes up blank. also how can I console log the entire contents of the object to see its structure? thirdly - this object, in this manner as I can tell is available through ejs, however not to core javascript and i can only access it using the ejs <% %> tags. is this a correct understanding?

Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
Ray_Hack
  • 973
  • 2
  • 9
  • 27

2 Answers2

4

You can use Object.keys():

const buttonsdata = {
  "default": {
    "1": {
      "id": "alertmessages",
      "title": "Your Messages",
      "subtitle": "Tasks waiting for your attention",
      "image": "alert.png",
    },
    "2": {
      "id": "uploadr",
      "title": "Upload",
      "subtitle": "Upload",
      "image": "baskets.png",
    }
  }
};

Object.keys(buttonsdata.default).forEach(function (key) {
  console.log(buttonsdata.default[key].id);
});

Now, according to your code, in the view should work like this:

<ul>
<% Object.keys(buttonsdata.default).forEach(function(key) { %> 
    <li><%= buttonsdata.default[key].id %></li>
<% }) %>
</ul>
Ron
  • 5,900
  • 2
  • 20
  • 30
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
1
  1. Your json contains only objects, it doesn't have any arrays in it, so you won't be able to use buttonsdata.length

  2. Displaying the whole object - display the object from within your controller, not your template. Look at this answer to see how

  3. this object is available through ejs - yes, that's a correct understanding - I assume that by core javascript you mean the javascript that's executed in the browser. The whole ejs template is processed on the backend.

Community
  • 1
  • 1
Tudor Constantin
  • 26,330
  • 7
  • 49
  • 72