在javascript中搜索json数组

时间:2015-07-06 10:36:04

标签: javascript json

我正在处理一个json数组并对其进行搜索。代码似乎没问题,但没有给出输出。这是我的代码

var restaurants = [
        {"restaurant" : { "name" : "McDonald's", "food" : "burger",      "drink" : "coke", "content" : "Lorem ipsum dolor sit amet" }},
        {"restaurant" : { "name" : "KFC", "food" : "chicken", "drink" : "pepsi", "content" : "Lorem ipsum dolor sit amet" }},
        {"restaurant" : { "name" : "Pizza Hut",  "food" : "pizza", "drink" : "sprite", "content" : "Lorem ipsum dolor sit amet" }},
        {"restaurant" : { "name" : "Dominos",  "food" : "pizza", "drink" : "root beer", "content" : "Lorem ipsum dolor sit amet" }},
        {"restaurant" : { "name" : "Popeyes",  "food" : "chicken", "drink" : "mist", "content" : "Lorem ipsum dolor sit amet" }}
      ];

我的搜索方法是

function filter( restaurants, food, drink) { 

var result = [];

for( var i= 0, len = restaurants.length; i < len; i++) {
    var el = restaurants.restaurant[i];

    if( el.food === food && el.drink === drink ) {
        result.push( el );
    }
}

return result;
}

但在控制台中显示Uncaught TypeError: Cannot read property 'length' of undefined。这个功能出了什么问题?我如何进行完整的搜索?是关于字符串长度函数吗?

3 个答案:

答案 0 :(得分:1)

此行中有错误

var el = restaurants.restaurant[i];

必须是

var el = restaurants[i].restaurant;

JsBin Example

我建议您使用lodash来处理数组。它将使您的代码更简单。 JsBin Example with lodash

答案 1 :(得分:0)

var el = restaurants.restaurant[i];

您选择未定义的restaurants.restaurant的元素[i],因为restaurants是您的数组,restaurant是包含在所有数组元素中的对象。

使用

var el = restaurants[i].restaurant;

用它显示

JSON.stringify(filter(restaurants,"burger","coke"))
"[{"name":"McDonald's","food":"burger","drink":"coke","content":"Lorem ipsum dolor sit amet"}]"    filter(restaurants, "burger","coke")

答案 2 :(得分:0)

restaurants是一个数组,你必须使用index而不是属性来访问它的元素。工作代码:

var restaurants = [
        {"restaurant" : { "name" : "McDonald's", "food" : "burger",      "drink" : "coke", "content" : "Lorem ipsum dolor sit amet" }},
        {"restaurant" : { "name" : "KFC", "food" : "chicken", "drink" : "pepsi", "content" : "Lorem ipsum dolor sit amet" }},
        {"restaurant" : { "name" : "Pizza Hut",  "food" : "pizza", "drink" : "sprite", "content" : "Lorem ipsum dolor sit amet" }},
        {"restaurant" : { "name" : "Dominos",  "food" : "pizza", "drink" : "root beer", "content" : "Lorem ipsum dolor sit amet" }},
        {"restaurant" : { "name" : "Popeyes",  "food" : "chicken", "drink" : "mist", "content" : "Lorem ipsum dolor sit amet" }}
      ];

function filter( restaurants, food, drink) { 
    var result = [];
    for( var i= 0, len = restaurants.length; i < len; i++) {
        var el = restaurants[i].restaurant; // changed here from - var el = restaurants.restaurant[i];
        if( el.food === food && el.drink === drink ) {
            result.push( el );
        }
    }
    return result;
    }

filter(restaurants,"burger","coke");