So I need to access the key value "key" in this object:
{
"__v": 0,
"_id": "5317b71c902ff0080046349f",
"user": "530ef48599c41200009bad9f",
"email": "[email protected]",
"btcId": "9HjBb9eUhyXMKuVxSrTSkg",
"name": "Bitcoin Payments",
"dlFile": "a43ca076-4802-4cca-9648-82b2569ffc60.docx",
"key": "3518d5ce-badf-495c-a08f-dc28bb6d8a64",
"created": "2014-03-05T23:45:32.480Z"
}
but this code doesn't work:
console.log(body.key) -> Undefined
console.log(body['key'] -> undefined
console.log(body['"key"'] -> undefined
body is where the object is stored.
I think it has something to do with the key's being strings? or having the "" around them? However I'm not creating the body variable so I can't control this...
Any ideas on how to make it work?
So I need to access the key value "key" in this object:
{
"__v": 0,
"_id": "5317b71c902ff0080046349f",
"user": "530ef48599c41200009bad9f",
"email": "[email protected]",
"btcId": "9HjBb9eUhyXMKuVxSrTSkg",
"name": "Bitcoin Payments",
"dlFile": "a43ca076-4802-4cca-9648-82b2569ffc60.docx",
"key": "3518d5ce-badf-495c-a08f-dc28bb6d8a64",
"created": "2014-03-05T23:45:32.480Z"
}
but this code doesn't work:
console.log(body.key) -> Undefined
console.log(body['key'] -> undefined
console.log(body['"key"'] -> undefined
body is where the object is stored.
I think it has something to do with the key's being strings? or having the "" around them? However I'm not creating the body variable so I can't control this...
Any ideas on how to make it work?
Share Improve this question asked Mar 5, 2014 at 23:51 gbachikgbachik 1,7063 gold badges17 silver badges30 bronze badges 6-
1
The first and second should work, unless
body
isn't what you think it is. Tryconsole.log(body)
to see what is really is. – Joseph Commented Mar 5, 2014 at 23:52 - What do you mean they have quotes, do you have a string or an object. – adeneo Commented Mar 5, 2014 at 23:52
-
1
@gbachik Do you have
var body = { "__v": 0, "_id": "5317b71c902ff0080046349f", "user": "530ef48599c41200009bad9f", "email": "[email protected]", "btcId": "9HjBb9eUhyXMKuVxSrTSkg", "name": "Bitcoin Payments", "dlFile": "a43ca076-4802-4cca-9648-82b2569ffc60.docx", "key": "3518d5ce-badf-495c-a08f-dc28bb6d8a64", "created": "2014-03-05T23:45:32.480Z" }
? – Abraham Hamidi Commented Mar 5, 2014 at 23:53 -
1
Looks like you have JSON data, not a JS object. If so, you should
JSON.parse()
it. – cookie monster Commented Mar 5, 2014 at 23:56 -
To verify, do this
console.log(typeof body);
. If it's JSON data, you'll get"string"
. – cookie monster Commented Mar 5, 2014 at 23:59
1 Answer
Reset to default 6However I'm not creating the body variable so I can't control this...
This sounds like a GET
request, so if it's JSON data, parse it with JSON.parse
:
console.log(JSON.parse(body).key)