簡體   English   中英

如何在Json文件中搜索和匹配2個輸入字段值,如果找到匹配項,則從同一json對象返回第3個鍵值

[英]How to Search and Match 2 input fields values in Json file and if match found return 3rd Key Value from same json object

我有2個輸入字段,用戶將在其中輸入取件和交貨區域名稱。當用戶完成第二次輸入(交貨或取件-無序列)時,我想啟動一個過程,從JSON文件中搜索兩個輸入值,如果匹配對於這兩個輸入,找到相關的價格。 我能夠捕獲兩個輸入中的值,但是我需要一種方法將它們與JSON文件進行比較,並在成功顯示比賽價格時進行比較。 在構造函數中定義的方法,為我提供了Json文件中的所有對象。

注意。 查找匹配過程不會以單擊開始,而是以(更改)值開始。

模板

<div class="form-group">
  <input class="form-control" id="pickupSuburb" (change)="onSelectedSuburb($event)" placeholder=" Pickup Suburb Here"   [(ngModel)]="pickupSuburb"  >
</div>

<div class="form-group">
  <input list="suburb" class="form-control" id="deliverySuburb" (change)="onSelectedSuburb($event)" placeholder=" Delivery Suburb Here" [(ngModel)]="deliverySuburb" >
</div>

零件

import {Component, OnInit, ElementRef } from '@angular/core';
import 'rxjs/add/operator/map'
import { FormControl } from '@angular/forms';
import {Http} from '@angular/http';

@Component({
  selector: 'app-sending',
  templateUrl: './sending.component.html',
  styleUrls: ['./sending.component.css'],
  providers: [SuburbsService, AutoCompleteSuburbs, CapitalizePipe ],
})

export class SendingComponent implements OnInit {
  priceList = [];

  constructor(private elm: ElementRef, private http: Http) {
    http.get('./assets/zoneRates.json').subscribe(response => {
      this.priceList = response.json();
    })
  }

  ngOnInit () {}

  public onSelectedSuburb(event) {
    const pickupArray = this.elm.nativeElement.querySelector('#pickupSuburb').value.slice(1).slice(-3);
    const deliveryArray = this.elm.nativeElement.querySelector('#deliverySuburb').value.slice(1).slice(-3);}

傑森樣品

[{
    "pickup": "SYD",
    "delivery": "QC4",
    "weight": "25",
    "price": "6.25"
  }, {
    "pickup": "SYD",
    "delivery": "QC6",
    "weight": "25",
    "price": "6.25"
  }, {
    "pickup": "SYD",
    "delivery": "QC7",
    "weight": "25",
    "price": "6.25"
  }, {
    "pickup": "SYD",
    "delivery": "ADL",
    "weight": "25",
    "price": "6.25"
  }]

您可以使用OnChanges生命周期掛鈎,並使用array.prototype.find搜索產品數組。 我在任何地方都看不到您聲明該表單,因此我假設您使用的是反應式表單。 我建議切換到動態表單( https://angular.io/guide/dynamic-form ),因為這將使獲取值更加容易。

我的答案是假設您進行此開關並在組件中聲明了pickupInputdeliveryAreaInput屬性,這些屬性綁定到表單上的關聯輸入。 如果您需要堅持使用reactForms,則必須以其他方式獲取這些值。

export class sendingComponent implements onChanges, onInit {
  private pickupInput: FormControl = new FormControl('', Validators.required); // You may need different validation than this.
  private deliveryAreaInput: FormControl = new FormControl('', Validators.required); // again your validation may differ.

  /**
   * Checks if either pickupInput or deliveryAreaInput are in the changes object.
   * If either key is included pass both values to the searchJson method and store the response in a match property
   * If match is truthy show the price
   * @param {SimpleChanges} changes
   */ 
  ngOnChanges(changes: SimpleChanges) {
    if (changes.pickupInput || changes.delieveryAreaInput) {
      const match: any = this.searchJson(this.pickupInput.value, this.deliveryAreaInput.value);
      if (match) {
        this.showPrice = true; // Use this with an ngIf in your template
      }
    }
  }

  /**
   * Use Array.prototype.find to search through the priceList array for any products that have a matching pickup and delivery area.
   * Array.prototype.find returns either the matching value or undefined if no matches are found.
   * @param {string} pickup
   * @param {string} deliveryArea
   * @return {?} either the matching value or undefined
   */
  private searchJson(pickUp: string, deliveryArea: string): any {
    return this.priceList.find(price => {
      return price.pickup === pickUp && price.delivery === deliveryArea;
    });
  }
}

不過,我會擔心對變更進行搜索。 這將導致在每次按鍵時搜索整個產品目錄,如果目錄較長,則會明顯變慢。 更好的解決方案是引入一個按鈕或搜索焦點而不是更改(盡管這將要求用戶明顯地聚焦)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM