如何使用Javascript或jQuery过滤JSON数据?
这是我的JSON数据:
[{"name":"Lenovo Thinkpad 41A4298","website":"google"},
{"name":"Lenovo Thinkpad 41A2222","website":"google"},
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"},
{"name":"Lenovo Thinkpad 41A424448","website":"google"},
{"name":"Lenovo Thinkpad 41A429rr8","website":"ebay"},
{"name":"Lenovo Thinkpad 41A429ff8","website":"ebay"},
{"name":"Lenovo Thinkpad 41A429ss8","website":"rediff"},
{"name":"Lenovo Thinkpad 41A429sg8","website":"yahoo"}]JavaScript:
obj1 = JSON.parse(jsondata);现在我只想要包含网站的名称和网站数据等于"yahoo"。
发布于 2014-05-18 10:42:50
这就是你应该怎么做的:(对于谷歌搜索)
$([
{"name":"Lenovo Thinkpad 41A4298","website":"google222"},
{"name":"Lenovo Thinkpad 41A2222","website":"google"}
])
.filter(function (i,n){
return n.website==='google';
});更好的解决方案:(萨勒曼)
$.grep( [{"name":"Lenovo Thinkpad 41A4298","website":"google"},{"name":"Lenovo Thinkpad 41A2222","website":"google"}], function( n, i ) {
return n.website==='google';
});http://jsbin.com/yakubixi/4/edit
发布于 2014-05-18 10:48:50
不需要jQuery,除非您针对旧的浏览器,并且不想使用shims。
var yahooOnly = JSON.parse(jsondata).filter(function (entry) {
return entry.website === 'yahoo';
});在ES2015中:
const yahooOnly = JSON.parse(jsondata).filter(({website}) => website === 'yahoo');发布于 2018-02-02 14:01:03
以下代码适用于我:
var data = [{"name":"Lenovo Thinkpad 41A4298","website":"google"},
{"name":"Lenovo Thinkpad 41A2222","website":"google"},
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"},
{"name":"Lenovo Thinkpad 41A424448","website":"google"},
{"name":"Lenovo Thinkpad 41A429rr8","website":"ebay"},
{"name":"Lenovo Thinkpad 41A429ff8","website":"ebay"},
{"name":"Lenovo Thinkpad 41A429ss8","website":"rediff"},
{"name":"Lenovo Thinkpad 41A429sg8","website":"yahoo"}]
var data_filter = data.filter( element => element.website =="yahoo")
console.log(data_filter)
https://stackoverflow.com/questions/23720988
复制相似问题