简体   繁体   English

循环遍历JSON项目,无论JSON对象是否具有多个数组

[英]Loop over JSON items whether JSON object has multiple arrays or not

I have a working version of a function to loop through a single array in a JSON object, eg 我有一个函数的工作版本,可以循环通过JSON对象中的单个数组,例如

[{
    "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 eg 现在,我需要更改此函数以允许单个或多个数组,例如

{
    "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个数组(如第一个示例中的数组)或多个数组(如第二个示例中的数组),以及有关如何扩展功能以能够遍历所有项的任何建议/指导它有1个数组还是多个数组?

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 : 编辑:如果要遍历(只是json解码的)对象的所有属性,则当它不是数组时,可以执行以下操作:

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"}, ... ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM