ben*_*ron 2 javascript arrays jquery
我有一个JavaScript对象,我用它来存储一个用户的数据,如下所示:
output = {
id: "444",
trial: [1, 2, 3, 4, 5, 6, 7, 8, 9],
points: [0, 100, 50, 50, 0, 0, 0, 100, 50]
}
Run Code Online (Sandbox Code Playgroud)
我要的是查询/过滤这些对象,例如,提取所有试验的数字output.trial哪里output.points > 50.
我在另一篇文章中发现了这个,但它并不是我想要的(它返回一个空数组).
var result = $.grep(output, function(v) {
return v.points > 50;
});
Run Code Online (Sandbox Code Playgroud)
换句话说,我想给出一些条件并接收我的对象名称的实例,这是真的(最好是数组).在这个例子中:
result_after_query = [2, 8]
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
您可以使用Array.prototype.filter方法:
var output = {
id: "444",
trial: [1, 2, 3, 4, 5, 6, 7, 8, 9],
points: [0, 100, 50, 50, 0, 0, 0, 100, 50]
};
var result = output.trial.filter(function(el, i) {
return output.points[i] > 50;
});
document.write(JSON.stringify(result));Run Code Online (Sandbox Code Playgroud)