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?

1 Answer 1

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"}, ... ]
}
Sign up to request clarification or add additional context in comments.

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.