Keith C. Keith C. - 4 months ago 5
Javascript Question

JS access an array with in an object

I have a variable holding a string of validated JSON. The JSON is a set of strings each with a value of an array. I'd like to access the string and each array value.

var json_string = {"div-1":["div-1A", "div-1B"], "div-2":["div-2A", "div-2B"]};

//Run some code to get the following result:
console.log("div-1" has "div-1A");
console.log("div-1" has "div-1B");
console.log("div-2" has "div-2A");
console.log("div-2" has "div-2B");

I have tried a bunch of different things but nothing seems to work right. Additionally, I get a weird functionality. If I do the following:


I randomly get the following results for each page refresh :

div-1A //initial load
div-1C //refresh 1
div-1A //refresh 2
div-1B //etc
div-1A //etc

Any ideas how I can get what I am after?


You can first retrieve the values from keys and then use forEach to get their value

var json_string = {"div-1":["div-1A", "div-1B"], 
                  "div-2":["div-2A", "div-2B"]
for(var key in json_string){
 var _getValue = json_string[key]
 if(_getValue.constructor===Array){  // Checking if it is an array