需要使用IF语句和JSON进行协助

时间:2016-11-14 17:51:42

标签: jquery json

我试图找出如何使用if语句在页面上过滤我的JSON结果。每个配方都有自己的类别,我试图能够根据类型类别类型和其他参数来过滤信息。我只提供了一些代码供人们使用,但是当我运行时,我什么也得不到。这是我的代码:

$.each(json, function(i, item) {
	if (item.recipeCategories == "fall") { 
       //show correct items in div
    }
});
var json = 
    
[
   {   
	   "recipeName":"Crispy Zucchini Fritte with Lemon Aioli",
	   "recipeCategories":[
             "appetizers",
		   	 "spring"
       ],
	},
    {   
	   "recipeName":"Hummus Tahini",
	   "recipeCategories":[
             "desserts",
		   	 "fall"
       ],
	}
]

2 个答案:

答案 0 :(得分:1)

这一行:

if (item.recipeCategories == "fall") {

检查item.recipeCategories =="fall"是否为recipeCategories,但对象数组中的if (item.recipeCategories.indexOf("fall") !== -1) { 本身就是一个数组。您可能需要indexOf(或真正的现代JavaScript,includes):

if (item.recipeCategories.includes("fall")) {

从ES2016开始(并可以填充):

var json = [
    {
        "recipeName": "Crispy Zucchini Fritte with Lemon Aioli",
        "recipeCategories": ["appetizers", "spring"],
	},
    {
        "recipeName": "Hummus Tahini",
        "recipeCategories": ["desserts", "fall"],
    }
];
$.each(json, function(i, item) {
    if (item.recipeCategories.indexOf("fall") != -1) {
        $("<div>").text(item.recipeName).appendTo(document.body);
    }
});

示例:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
import { Injectable } from "@angular/core";
import { ActivatedRoute, Router } from '@angular/router';
import { Http, Headers, Response, Request, RequestMethod, URLSearchParams, RequestOptions } from "@angular/http";
import {Observable} from 'rxjs/Rx';
import { Constants } from './constants';
declare var $: any;

@Injectable()
export class HttpClient {
  requestUrl: string;
  responseData: any;
  handleError: any;

  constructor(private router: Router, 
  private http: Http, 
  private constants: Constants, 
  ) {
    this.http = http;
  }

  postWithFile (url: string, postData: any, files: File[]) {

    let headers = new Headers();
    let formData:FormData = new FormData();
    formData.append('files', files[0], files[0].name);
    // For multiple files
    // for (let i = 0; i < files.length; i++) {
    //     formData.append(`files[]`, files[i], files[i].name);
    // }

    if(postData !=="" && postData !== undefined && postData !==null){
      for (var property in postData) {
          if (postData.hasOwnProperty(property)) {
              formData.append(property, postData[property]);
          }
      }
    }
    var returnReponse = new Promise((resolve, reject) => {
      this.http.post(this.constants.root_dir + url, formData, {
        headers: headers
      }).subscribe(
          res => {
            this.responseData = res.json();
            resolve(this.responseData);
          },
          error => {
            this.router.navigate(['/login']);
            reject(error);
          }
      );
    });
    return returnReponse;
  }
}

答案 1 :(得分:1)

由于recipeCategories是一个数组,因此您可以使用indexOf

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

请参阅此bin以了解用法:https://jsbin.com/xilarewafe/edit?html,js,output