How to select child keys in a JSON object array with Javascript / Nodejs in 2020

This is harder to find a clean example for than it should be on the Mozilla or W3 docs so here’s a modern ES6 Javascript / NodeJS solution for you! If you want to select the JSON data from a file, scroll further down for an example. You can test these examples in browser dev tools console or using the node interpreter.

 

Selecting JSON array child key values from a JSON object variable

tmpJsonArray = {
	"api_keys": [{
		"id": "1",
		"api_service_name": "amazon",
		"api_key_value": "a888332131454047678908158"
	}, {
		"id": "2",
		"api_service_name": "netflix",
		"api_key_value": "hh3aa88833454047678908158"
	}]
}
function selectAPIKeyValue() {

    for (var api_key of tmpJsonArray.api_keys)
        console.log(api_key.api_key_value) // print the value of api_keys.api_key_value
}

selectAPIKeyValue();

Expected Output:

$ node jsonObjectLearning.js
a888332131454047678908158
hh3aa88833454047678908158

Selecting JSON array child key values from a JSON file

/* list_of_api_keys_to_use.json file contains:
{ "api_keys": [{ "id": "1", "api_service_name": "amazon", "api_key_value": "a888332131454047678908158" }, { "id": "2", "api_service_name": "netflix", "api_key_value": "hh3aa88833454047678908158" }] }
*/

var listOfAPIKeys = require('./list_of_api_keys_to_use.json');

function selectAPIKeyValue() {

    for (var api_key of listOfAPIKeys.api_keys)
        console.log(api_key.api_key_value)
}

selectAPIKeyValue();

Expected Output:

$ node jsonObjectLearning.js
a888332131454047678908158
hh3aa88833454047678908158

Leave a Reply

You are currently viewing How to select child keys in a JSON object array with Javascript / Nodejs in 2020