0

I have created a jsfiddle with the help from this post. The recursive loop works with JSON raw data but doesn't work when the JSON data is read from PHP array.

var notes = '<?php echo json_encode($notes); ?>';

console.log(notes); // displays JSON raw data (used in jsfiddle)

After looping through the data, I wanted to get specific output based on type: Subject, Topic, Subtopic, Concept, Paragraph.

How do I solve this issue?

Community
  • 1
  • 1
h4kl0rd
  • 625
  • 1
  • 10
  • 23

2 Answers2

3

Remove the quotes: var notes = <?php echo json_encode($notes); ?>;

The quotes make it a string, not an object.

If you want to write it as a string, then you need to convert it from the string into JSON:

var notes = JSON.parse('<?php echo json_encode($notes); ?>');

To access object properties in a for loop, do this:

for (var key in myObj) {
  console.log(myObj[key]);
}

You can access object propertied with dot notation or bracket notation. Dot notation is often considered to be cleaner, though it is more limited. Consider this object:

var myObj = {
  foo : "some value",
  bar : "some other value",
  "1&^@" : "this value's key is invalid!"
};

To access the properties that have keys that are valid javascript variable names, you can use dot notation like this:

console.log(myObj.foo); //"some value"
console.log(myObj.bar); //"some other value"

The third property will not work this way. As it contains otherwise invalid characters, it had to be created as a string and must be accessed as a string, so use bracket notation:

console.log(myObj['1&^@']);

Another cool thing about bracket notation is that you can use variables as the key name. (also see the for loop above).

var foo = 'bar';

var myObj = {
  bar : 123
};

console.log(myObj[foo]); //123

This works because foo has a value of 'bar', so myObj[foo] is equivalent to myObj['bar'] or myObj.bar.

m59
  • 43,214
  • 14
  • 119
  • 136
  • After looping through the values, how do I get content (Physics) based on type (Subject). Eg. {"id":"750","content":"Physics","type":"Subject"} – h4kl0rd Jan 19 '14 at 08:33
  • I greatly updated my answer. In your answer's example, dot notation would be typically preferred. – m59 Jan 19 '14 at 15:10
0

With @m59's help I managed to iterate through the JSON data and get specific data. Here's the jsfiddle.

if (obj['type'] == 'Subject') {
     body += 'SubjectId:' + obj['id'] + '<br>';
     body += 'SubjectContent:' + obj['content'] + '<br>';

     var topics = obj['children'];
     var topic;
     for (topic in topics) {
         body += 'topicId:' + topics[topic]['id'] + '<br>';
         body += 'topicContent:' + topics[topic]['content'] + '<br>';
         body += 'topicType:' + topics[topic]['type'] + '<br>';
     }
}
h4kl0rd
  • 625
  • 1
  • 10
  • 23