kjsmita6
kjsmita6

Reputation: 464

Printing JSON properties

I am currently trying to send a user information about a JSON object that I've recieved from an API. An example of the format is

[
{
    "lang_code":        "eng",
    "site_language":    "1",
    "name":         "English"
},
{
    "lang_code":        "afr",
    "site_language":    "1",
    "name":         "Afrikaans"
},
{
    "lang_code":        "ale",
    "site_language":    "0",
    "name":         "Aleut"
},
]

I want to be able to access the lang_code property of every single language and send it. I've tried to use

var languageCodes;
var languageResult = body.lang_code; //body is the result from a request.get({ ... })
for(var codes in languageResult) {
    languageCodes = languageResult[codes];
}

Object.keys does nothing, as it just sends 72 numbers to me. Any thoughts?

On a side note, I also want people to be able to type "! languages [my command] eng", for example, and it sends "English" instead of just sending "1 is [object Object]".

Upvotes: 1

Views: 77

Answers (2)

ThisClark
ThisClark

Reputation: 14823

I looped through your lang_codes like this:

var codes = [{"lang_code":"eng","site_language":"1","name":"English"}, {"lang_code":"afr","site_language":"1","name":"Afrikaans"},{"lang_code":"ale","site_language":"0","name":"Aleut"}];

for(var i = 0; i < codes.length; i++) {
    console.log(codes[i].lang_code);
}

Upvotes: 0

Phil
Phil

Reputation: 164767

Assuming body is the array at the top of your question, if you just want an array of all the language codes, this should suffice

var languageCodes = body.map(function(lang) {
    return lang.lang_code;
});

var body = [{
  "lang_code": "eng",
  "site_language": "1",
  "name": "English"
}, {
  "lang_code": "afr",
  "site_language": "1",
  "name": "Afrikaans"
}, {
  "lang_code": "ale",
  "site_language": "0",
  "name": "Aleut"
}];

var languageCodes = body.map(function(lang) {
  return lang.lang_code;
});

document.getElementById('out').innerHTML = JSON.stringify(languageCodes);
<pre id="out"></pre>

Upvotes: 1

Related Questions