-2

I would like to iterate through a json object which I got from var jsonObj json_encode( <?php echo $php_array ?>);. This looks to me like a different format to what most people have. For example, w3schools shows this as a json object:

{
    "employees": [
        { "firstName":"John" , "lastName":"Doe" }, 
        { "firstName":"Anna" , "lastName":"Smith" }, 
        { "firstName":"Peter" , "lastName":"Jones" }
    ]
}

Mine seems to have completely structure:

{"PINEFOREST JEWELRY":
    ["3034.25","2002-01-02"],
"AMBERS DESIGN":
    ["2034.75","2002-01-02"],
"ELEGANT JEWELERS":
    ["206","2002-01-02"],
"SALEM'S JEWELERS":
    ["406","2002-01-02"]}

Am I able to iterate through this?

brietsparks
  • 4,776
  • 8
  • 35
  • 69
  • See this answer: http://stackoverflow.com/questions/23310353/how-to-read-json-result-in-jquery/23310376#23310376 – toesslab May 29 '14 at 14:12

3 Answers3

0

You can use a for in with a nested for

for (var key in data) {
    for (var i = 0; i < data[key].length; i++) {
        console.log(data[key][i]);
    }
}
Andy
  • 61,948
  • 13
  • 68
  • 95
tymeJV
  • 103,943
  • 14
  • 161
  • 157
0

You can use a for loop to iterate through the object's direct properties as follows:

var val;
for(var key in obj) {
    if(obj.hasOwnProperty(key)){
        val = obj[key];
        console.log(val);
    }
}
lucasjackson
  • 1,515
  • 1
  • 11
  • 21
0

Yes you can itterate through it as it is valid json.

To start of you need to convert the json into something javascript can itterate over, which you can do with JSON.parse() (MDN). Im assuming that the 'json' you described above is a string of 'json' so:

var jewellery = JSON.parse(myJson); // replace myJson with whatever variable is holding your json

At this point you have an object which you can itterate over. One of the easiest ways to do this would be by using Object.keys() (MDN) and Array.forEach() (MDN) like so:

Object.keys(jewellery).forEach(function (key) {
    console.log(key); // would log 'PINEFOREST JEWELRY' the first time
    jewellery[key].forEach(function (price) {
        console.log(price); // Should log '3034.25' the first time
    }
});

Give that a try, otherwise you could still use the other solutions other people have submitted, either or would work. This is how I would do it though!!

iLikePrograms
  • 470
  • 2
  • 9
  • Be careful with the forEach function as it isn't supported in some browsers like IE8 (http://caniuse.com/#search=forEach) – lucasjackson May 29 '14 at 18:40
  • That can be a concern yes, which is why I said give it a try and if it doesn't work then use the other solutions people have submitted :) – iLikePrograms May 29 '14 at 19:11