如何在Json文件中搜索和匹配2个输入字段值,如果匹配,则从同一个json对象返回第3个键值

时间:2017-07-13 22:25:19

标签: javascript json angular typescript

我有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);}

Json Sample

[{
    "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"
  }]

1 个答案:

答案 0 :(得分:0)

您可以使用OnChanges生命周期钩子并使用array.prototype.find搜索产品数组。我没有看到你宣布表格的任何地方,所以我假设你正在使用被动表格。我建议切换到动态表单(https://angular.io/guide/dynamic-form),因为它会使值更容易。

我的回答是假设您进行此切换并在组件中声明了pickupInputdeliveryAreaInput属性,这些属性绑定到表单上的关联输入。如果你需要坚持使用反应形式,你必须以其他方式获得这些价值。

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;
    });
  }
}

我会担心这个改变的搜索。这将导致在每个按键上搜索整个产品目录,如果目录很长,则会明显变慢。更好的解决方案是引入按钮或进行焦点搜索而不是更改(尽管这需要用户明确关注)。