2

I have a working version of a function to loop through a single array in a JSON object, e.g.

[{
    "Name": "John",
    "Surname": "Johnson"
}, {
    "Name": "Peter",
    "Surname": "Johnson"
}]

sample function:

function FindName(NameToFind, data1) {

    objData = JSON.parse(data1);

    for (var i = 0; i < objData.length; i++) {

        var Name = objData[i].Name;

        if (Name == NameToFind) {
            alert("found!");
        }
    }
}

Now I need to change this function to allow for either single OR multiple arrays e.g.

{
    "Table1": [{
        "Name": "John",
        "Surname": "Johnson"
    }, {
        "Name": "Peter",
        "Surname": "Johnson"
    }],

    "Table2": [{
            "Name": "Sarah",
            "Surname": "Parker"
        },
        {
            "Name": "Jonah",
            "Surname": "Hill"
        }
    ]
}

Is there a way to determine whether the object has 1 array (like in first example) or more than one arrays (like in 2nd example), and any advice/guidance on how to extend the function to be able to loop through all the items whether it has 1 array or multiple arrays?

Mike
  • 14,010
  • 29
  • 101
  • 161
Peter PitLock
  • 1,823
  • 7
  • 34
  • 71

1 Answers1

4

Your first object is an array, the second one isn't.

You can test if your argument is an array, or even just test

if (objData[0]) // that's an array

EDIT : if you want to iterate over all properties of a (just json decoded) object, when it's not an array, you can do this :

for (var key in objData) {
    var value = objData[key];
    // now use the key and the value
    // for example key = "Table1"
    // and value = [{"Name":"John","Surname":"Johnson"}, ... ]
}
Community
  • 1
  • 1
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • made good progress now thank you, so its {object:[{Array},{Array}], {object:[{Array},{Array}]} , and "for (var i = 0; i < objData.length; i++) " loops through each arraylist item, how can i loop through all the objects please? – Peter PitLock Aug 24 '12 at 11:46