簡體   English   中英

如何過濾 JavaScript 對象數組?

[英]How to filter an array of JavaScript objects?

假設我有以下對象

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,
  }
]

我怎樣才能過濾這個,例如 return all where hidden = 1

干杯

使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM