myArray = [{'id':'73','foo':'bar 22'},
{'id':'45','foo':'bar'},
{'id':'46','foo':'area'},
{'id':'47','foo':'line'}]
var allbars = myArray && myArray.filter(function( obj ) {
return obj.foo == "bar";
});
过滤后得到
allbars = [{'id':'45','foo':'bar'}]
但我需要 foo 键中存在所有条形图
Expected output is(in the key foo i have bar, bar22 both are expecting in the output but i can able to get only bar)
allbars = [{'id':'45','foo':'bar'}, {'id':'73','foo':'bar 22'}]
最佳答案
你应该在过滤条件中使用.includes()
myArray = [{'id':'73','foo':'bar 22'},
{'id':'45','foo':'bar'},
{'id':'46','foo':'area'},
{'id':'47','foo':'line'}]
var allbars = myArray && myArray.filter(obj => obj.foo.includes("bar"));
console.log(allbars)
如果你想让它兼容浏览器 (IE),你可能想使用 .indexOf()
myArray = [{'id':'73','foo':'bar 22'},
{'id':'45','foo':'bar'},
{'id':'46','foo':'area'},
{'id':'47','foo':'line'}]
var allbars = myArray && myArray.filter(obj => obj.foo.indexOf("bar") > -1);
console.log(allbars)
关于javascript - 如何使用javascript根据数组中的键进行过滤?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50667086/