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
.