EN
JavaScript - how to access first element of JSON object array?
1
answers
0
points
I have s20_message which contains only one object.
var req = {
s20_message: '[{"message":"incoming","uid":31227}]',
};
How do I access its message property?
1 answer
0
points
Use [0] to access the first element, but in your case the s20_messages contains a string, not an array, so s20_messages[0] will just get you the first character - '['.
The solution would be to use JSON.parse() on the string first.
Practical example:
// ONLINE-RUNNER:browser;
var req = {
s20_message: '[{"message":"incoming","uid":31227}]',
};
var s20_message = JSON.parse(req.s20_message);
var result = s20_message[0];
console.log(JSON.stringify(result)); // { message: 'incoming', uid: 31227 }
Note:
The
JSON.stringify()method in this example was used only to print result object in the console.
References
0 comments
Add comment