从下拉列表中过滤数据

时间:2016-08-15 07:44:53

标签: rxjs5

我想根据选择框的选择值过滤数据。

<select id="testDD">
    <option value="local">Local</option>
    <option value="international">Internationl</option>
</select>
<div id="list"><!-- List Items to be generated from #testDD value --></div>

我有像这样的数据对象

var data = [
    {type: 'local', name: 'abc1', location: 'xyz1'},
    {type: 'local', name: 'abc2', location: 'xyz2'},
    {type: 'international', name: 'abc3', location: 'xyz3'},
    {type: 'local', name: 'abc4', location: 'xyz4'},
    {type: 'local', name: 'abc5', location: 'xyz5'},
    {type: 'international', name: 'abc6', location: 'xyz6'},
    {type: 'international', name: 'abc7', location: 'xyz7'}
]

根据选择事件的变化过滤掉数据的理想方法是什么?

2 个答案:

答案 0 :(得分:0)

error_reporting(E_ALL);
ini_set('display_errors', 1);
const data = [
    {type: 'local', name: 'abc1', location: 'xyz1'},
    {type: 'local', name: 'abc2', location: 'xyz2'},
    {type: 'international', name: 'abc3', location: 'xyz3'},
    {type: 'local', name: 'abc4', location: 'xyz4'},
    {type: 'local', name: 'abc5', location: 'xyz5'},
    {type: 'international', name: 'abc6', location: 'xyz6'},
    {type: 'international', name: 'abc7', location: 'xyz7'}
];

const filterStream = Rx.Observable.fromEvent(document.getElementById('testDD'), 'change');


filterStream
  .map(evt => evt.target.value)
  .startWith(null)
  .subscribe(filterTypeName => {
    const filteredData = data.filter(d => d.type === filterTypeName || !filterTypeName);
    document.getElementById('list').innerText = JSON.stringify(filteredData);
  });

答案 1 :(得分:0)

使用主题和可观察对象可能是一种更清洁的方法。 This answer使用Subject来存储值,使用Observable观察值的更改,并使用函数来更改Subject的值。