[英]How to filter an array of JavaScript objects?
Lets say I have the following object假设我有以下对象
var ob = [
{
"id": 1,
"comment": "some comment",
"hidden": 0,
},
{
"id": 2,
"comment": "some comment",
"hidden": 1,
},
{
"id": 3,
"comment": "some comment",
"hidden": 1,
},
{
"id": 4,
"comment": "some comment",
"hidden": 0,
}
]
How can I filter this to say for example return all where hidden = 1我怎样才能过滤这个,例如 return all where hidden = 1
Cheers干杯
Use Array#filter
:使用
Array#filter
:
let arr = [ { "id": 1, "comment": "some comment", "hidden": 0, }, { "id": 2, "comment": "some comment", "hidden": 1, }, { "id": 3, "comment": "some comment", "hidden": 1, }, { "id": 4, "comment": "some comment", "hidden": 0, } ]; let res = arr.filter(x => x.hidden === 1); // or arr.filter(({hidden}) => hidden === 1); console.log(res);
var ob = [ { "id": 1, "comment": "some comment", "hidden": 0, }, { "id": 2, "comment": "some comment", "hidden": 1, }, { "id": 3, "comment": "some comment", "hidden": 1, }, { "id": 4, "comment": "some comment", "hidden": 0, }, { "id": 5, "comment": "some comment", "hidden": 2, } ] let result = ob.filter(x => x.hidden === 1); console.log("result for hidden properties 1",result) //Or you can use other condision. Just think like conditional operator but this is kind of different thing let result2 = ob.filter(x => x.hidden === 2); console.log("result for hidden properties 2",result2) //This condition only pass when hidden properties values 2. otherwise It won't filter and won't give your expected output , or result whatever you say.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.