如何在JSON循环中修复此查找? (无法读取未定义的属性'长度'未定义)

时间:2014-06-06 02:11:45

标签: javascript json

从@McGarnagle answer借用@ramesh question

我收到此错误的错误是什么:

Uncaught TypeError: Cannot read properly 'length' of undefined

javascript的JSON部分:

var obj = [
{
    "list": [
    {
        "name": "my Name",
        "id": 12,
        "type": "car owner"
    },
    {
        "name": "my Name2",
        "id": 13,
        "type": "car owner2"
    },
    {
        "name": "my Name4",
        "id": 14,
        "type": "car owner3"
    },
    {
        "name": "my Name4",
        "id": 15,
        "type": "car owner5"
    }]
}];

循环部分:

var results = [];
var searchField = "name";
var searchVal = "my Name";

for (var i=0 ; i < obj.list.length ; i++)
{
    if (obj.list[i][searchField] === searchVal) {
        results.push(obj.list[i]);
    }
}

0 个答案:

没有答案