Reputation: 813
I'm having issues accessing properties of a very simple object. As a novice programmer I suspect I have a simple misunderstanding of what exactly I'm working with.
Here is the code that is executing:
console.log(content);
console.log(content.title);
for (x in content){
console.log(content[x])
}
And here is the console response:
{"title":"test","description":"test"}
undefined
{
"
t
i
t
l
e
"
:
"
t
e
s
t
"
,
"
d
e
s
c
r
i
p
t
i
o
n
"
:
"
t
e
s
t
"
}
Any guidance would be greatly appreciated.
edit
The content object is being sent to the server via angular.js $http service as follows:
$http({
method:'post',
url:"/create/createContent",
params:{content:$scope.content}
}).
It seems the service moves the data in the JSON format.
Thanks everyone for the help! I really appreciate it.
Upvotes: 1
Views: 107
Reputation: 10473
This looks like content
is in fact a string and you are simply iterating over the characters in the string. Try this and see if it gives you what you want:
var contentJson = JSON.parse(content);
for (var x in contentJson) {
console.log(contentJson[x]);
}
This will parse the content
string into the appropriate JavaScript object and you should be able to access its properties.
Upvotes: 5
Reputation: 3974
Looks to me like the problem is how you are defining content
. Are you doing this?
content = '{"title":"test","description":"test"}';
or are you doing this?
content = {"title":"test","description":"test"};
Note: the first one has the entire thing wrapped in single quotes while the second has none.
Upvotes: 3
Reputation: 3334
Your object content is in JSON string form. Do this and you will get your desired results:
content = JSON.parse(content);
console.log(content);
console.log(content.title);
for (x in content){
console.log(content[x])
}
The way you can tell you are in JSON format is because of the quotations around the key values. If you were in object format, you wouldn't see the quotes.
See the difference below:
JSON string when output to console {"key1":1,"key2":"two"}
Object when output to console {key:1,key2:"two"}
Upvotes: 2