如何从JSON获取特定数据?

时间:2022-09-15 16:38:54

I have json file like this:

我有这样的json文件:

    [
      {"category":"food","id":"07","name":"hey"},
      {"category":"not","id":"06","name":"hey1"},
      {"category":"food","id":"05","name":"hey2"},
      {"category":"not","id":"04","name":"hey3"}
    ]

How to get all "names" that have "category":"food"? I am trying like this, but it doesnt work correctly.

如何获得所有具有“类别”的“名称”:“食物”?我这样想,但它无法正常工作。

    $.getJSON( "test.json", function( data ) {
      var items = [];
      $.each( data, function( key, val ) {
      if (val.category = "food"){
        items.push( "<li>" + val.name + "</li>" );
      }
    });

    $( "<ul/>", {
      "class": "my-new-list",
      html: items.join( "" )
    }).appendTo( "div" );
   });

1 个解决方案

#1


0  

You forgot to use the === operator (you can use == instead but it's considered better practice to use === ). You're code as written will include every element in the object because if (val.category = "food" ) will always evaluate to true and it will actually change the category value.

你忘了使用===运算符(你可以使用==代替但是使用===被认为是更好的做法)。您编写的代码将包含对象中的每个元素,因为if(val.category =“food”)将始终求值为true,并且它实际上将更改类别值。

Fix below.

修复如下。

if (val.category === "food"){
        items.push( "<li>" + val.name + "</li>" );
}

#1


0  

You forgot to use the === operator (you can use == instead but it's considered better practice to use === ). You're code as written will include every element in the object because if (val.category = "food" ) will always evaluate to true and it will actually change the category value.

你忘了使用===运算符(你可以使用==代替但是使用===被认为是更好的做法)。您编写的代码将包含对象中的每个元素,因为if(val.category =“food”)将始终求值为true,并且它实际上将更改类别值。

Fix below.

修复如下。

if (val.category === "food"){
        items.push( "<li>" + val.name + "</li>" );
}