glen maxwell
glen maxwell

Reputation: 203

How do get only first value from JSON object

I am having JSON Object in ajax response like that. I have to show these message on UI , for this I am using linke that .msg.result.word_containing_more_than_avg_chars It will works fine . But the problem is key is dynamic, in some case keyword_containing_more_than_avg_chars becomes title_containing_more_than_avg_Words . SO how do handle all case in such that I can get value part only irrespective of key .

Upvotes: 2

Views: 1356

Answers (3)

Ankur Soni
Ankur Soni

Reputation: 6018

Below code is more efficient,

Object.values(msg.result)[0];

Upvotes: 0

Rick Riggs
Rick Riggs

Reputation: 336

<html>
<head>
</head>
<body>
<div id="container"></div>

<script>

testobj = {"a" : "123", "b" : "234"};
testArray = [];
for (key in testobj) {
    testArray.push(testobj[key]);
}
document.getElementById('container').innerHTML = testArray[0];

</script>
</body>
</html>

I thought that I would answer this in a more generic way.

I saw it a little less efficient than the answer that is already here, however I personally iterate through them using a for loop, because it seems that at least in Chrome there was not an appropriate method for keys on the Object.

NoKeysMethodProof

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115222

Get the key using Object.keys method which returns an array of object property names.

msg.result[Object.keys(msg.result)[0]]

Upvotes: 3

Related Questions