JS过滤后台获取的原始数据

后台获取到的ajax的JSON数组,原始数据 

[

{"CostTime": "310", "FromStation": "上海"},

{"CostTime": "336", "FromStation": "北京"},

{"CostTime": "310", "FromStation": "上海"},

{"CostTime": "336", "FromStation": "北京"},

{"CostTime": "310", "FromStation": "上海"},

{"CostTime": "336", "FromStation": "北京"},

{"CostTime": "310", "FromStation": "上海"},

{"CostTime": "336", "FromStation": "北京"},

{"CostTime": "310", "FromStation": "上海"},

{"CostTime": "310", "FromStation": "上海"},

{"CostTime": "336", "FromStation": "北京"}

]


把FromStation为北京的数据过滤后生成新的数据

[

{"CostTime": "336", "FromStation": "北京"},

{"CostTime": "336", "FromStation": "北京"},

{"CostTime": "336", "FromStation": "北京"},

{"CostTime": "336", "FromStation": "北京"},

{"CostTime": "336", "FromStation": "北京"}

]


用JS或者JQ过滤具体方式是怎么样的。谢谢各位大牛指点下!


holdtom
浏览 866回答 3
3回答

慕田峪7331174

nArr = json.filter((item) => {   return item.FromStation == '北京'})

慕姐8265434

`var sourceData = [{"CostTime": "310", "FromStation": "上海"},{"CostTime": "336", "FromStation": "北京"},{"CostTime": "310", "FromStation": "上海"},{"CostTime": "336", "FromStation": "北京"},{"CostTime": "310", "FromStation": "上海"},{"CostTime": "336", "FromStation": "北京"},{"CostTime": "310", "FromStation": "上海"},{"CostTime": "336", "FromStation": "北京"},{"CostTime": "310", "FromStation": "上海"},{"CostTime": "310", "FromStation": "上海"},{"CostTime": "336", "FromStation": "北京"}];var currentData = sourceData.filter(x => {return x.FromStation === '北京';});console.log(currentData); // 你要的结果`

神不在的星期二

es6采用楼上的方法;es5写法:nArr = json.filter(function(item){    return item.FromStation === '北京';});不过建议做下简单的方法封装,将过滤关键词作为变量传入方便随时更换关键词function filterKey(key){    return json.filter(function(item){        return item.FromStation === key;    })}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript