如何根据用户输入过滤和显示JSON数据?

时间:2019-04-07 17:16:06

标签: jquery json

我将以下JSON数据存储在文件中:

[  
   {  
      "AA+A":0.3021,
      "A+AA":0.3021,
      "AAAU+AA":0.0677,
      "AA+AAAU":0.0677,
      "AABA+AAAU":0.092,
      "AAAU+AABA":0.092,
      "AAC+AABA":0.1713,
      "AABA+AAC":0.1713,
      "ULE+DXB":-0.0614,
      "DXB+ULE":-0.0614,
      "ULE+FLKR":0.308,
      "FLKR+ULE":0.308,
      "BNTCW+BAPR": "NaN"
   }
]

和以下格式:

 Stock1: -------
 Stock1: -------
      Submit

如何基于用户输入值(Stock1值和Stock2值)过滤JSON文件,并在div中显示数据,例如,如果数据不可用,则应该说“不可用” :

例如:

Stock1: AA
Stock1: A
Submit and display : 0.3021

Stock1: A
Stock1: AA
Submit and display : 0.3021

1 个答案:

答案 0 :(得分:0)

您可以使用in operator检查属性是否存在,然后根据该属性显示消息。

var data = [{"AA+A":0.3021,"A+AA":0.3021,"AAAU+AA":0.0677,"AA+AAAU":0.0677,"AABA+AAAU":0.092,"AAAU+AABA":0.092,"AAC+AABA":0.1713,"AABA+AAC":0.1713,"ULE+DXB":-0.0614,"DXB+ULE":-0.0614,"ULE+FLKR":0.308,"FLKR+ULE":0.308,"BNTCW+BAPR":"NaN"}];

// cache element to reuse
let $res = $('#res');
// cache elements and bind input event handlers
let $stks = $('#stock1,#stock2').on('input', function() {
  // iterate over elements to get value and then generate key
  let key = $stks.map(function() {
  // get value
    return this.value.trim();
  })
  // get result as an array and then join with + symbol
  .get().join('+');
  // show result baked on key
  $res.text(key in data[0] ? data[0][key] : 'Not found')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="stock1"><input id="stock2">
<div id="res"></div>