簡體   English   中英

如何從 javascript 中的數組中過濾掉 json object

[英]How to filter out json object from array in javascript

我有這個 JSON 響應我想過濾掉包含 arrays 類別中特定 id 的產品

[
 {
    "id": 7721,
    "name": "Grilled kebab corn tomato special",
    "purchase_note": "",
    "categories": [
        {
            "id": 50,
            "name": "All recipes",
            "slug": "0-all-recipes"
        },
        {
            "id": 94,
            "name": "Chef's Special",
            "slug": "chefs-special"
        }
    ]
 },
 {
    "id": 7722,
    "name": "Grilled kebab corn tomato special",
    "purchase_note": "",
    "categories": [
        {
            "id": 112,
            "name": "All recipes",
            "slug": "0-all-recipes"
        },
        {
            "id": 22,
            "name": "Chef's Special",
            "slug": "chefs-special"
        }
    ]
 }
]

這是一個示例,我想過濾掉類別數組中包含 id 112 的 object假設我想要上面給出的 JSON object 的結果

[
 {
    "id": 7722,
    "name": "Grilled kebab corn tomato special",
    "purchase_note": "",
    "categories": [
        {
            "id": 112,
            "name": "All recipes",
            "slug": "0-all-recipes"
        },
        {
            "id": 22,
            "name": "Chef's Special",
            "slug": "chefs-special"
        }
    ]
  }
]

在 JavaScript

謝謝 (:

這就是我嘗試過的,它正在過濾掉取決於對象內的字符串,但我找不到過濾掉取決於類別 id 的方法

這是我的嘗試

  menuData = the json response 

 menuData.filter(menuData => menuData.name == "Grilled kebab corn tomato special");

另外,我試過用這個

 menuData = the json response 

 menuData.filter(menuData => menuData.categories.map((o) => o.id) == 112);

 const filtered = data.filter((product) => { return product.categories.filter(cat => cat.id === 112) })

你可以簡單地這樣做:

const filtered = items.filter(item =>
  item.categories.filter(c => c.id == 112).length > 0

);

 const items = [{ "id": 7721, "name": "Grilled kebab corn tomato special", "purchase_note": "", "categories": [{ "id": 50, "name": "All recipes", "slug": "0-all-recipes" }, { "id": 94, "name": "Chef's Special", "slug": "chefs-special" } ] }, { "id": 7722, "name": "Grilled kebab corn tomato special", "purchase_note": "", "categories": [{ "id": 112, "name": "All recipes", "slug": "0-all-recipes" }, { "id": 22, "name": "Chef's Special", "slug": "chefs-special" } ] } ]; const filtered = items.filter(item => item.categories.filter(c => c.id == 112).length > 0 ); console.log(filtered);

console.log(your_array.filter(val =>  val.categories.find( item => item.id===112 ))  

這應該會給你答案。

所以你想要做的是過濾掉一些元素,如果他們的類別有一些類別匹配一些參數

所以你有了

menuData.filter(menu => {
  return !menu.categories.some(category => category.id === 112)
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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