0

I have this JSON:

{
  "projects": [
    {
      "id": 1,
      "children": [
        {
          "id": 2,
          "parent_id": 1,
          "project_name": "Carmichael Kitchen"
        },
        {
          "id": 3,
          "parent_id": 1,
          "project_name": "Carmichael Master Bedroom"
        },
        {
          "id": 4,
          "parent_id": 1,
          "project_name": "Carmichael Living Room"
        }
      ],
      "parent_id": 0,
      "project_name": "Carmichael"
    }
  ]
}

I am trying to display its contents with jQuery:

ajaxRequest.done(function(data) { 
    var jdata = JSON.parse(data);
    $.each(jdata, function(){ 
        $('#mydivname').append(projects.project_name);
    }
});

However, I can't seem to access project_name as it is 'undefined.'

What am I missing here? I feel it is something really simple that I am overlooking. Thank you in advance.

Rollor
  • 601
  • 1
  • 7
  • 17
  • You never defined a value for the `projects` variable. – trincot Mar 18 '19 at 15:08
  • Your each should be operating upon `jdata.projects`. – Taplar Mar 18 '19 at 15:09
  • You can use a combination of [.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) and [.flat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat) to get project names and append it accordingly. ajaxRequest.done(function(data) { var jdata = JSON.parse(data); const projects = jdata["projects"].map(x => x.children).flat().map(x => x.project_name); projects.forEach(x => { $('#mydivname').append(x); }); }); – Kunal Mukherjee Mar 18 '19 at 15:12
  • @KunalMukherjee if you want to show some code, put it in a fiddle and link it in the comments. It's very hard to read multi-line code in comments. – Taplar Mar 18 '19 at 15:15

0 Answers0