简体   繁体   中英

Access Javascript Object Property Issue

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.

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.

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.

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"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM