簡體   English   中英

如何根據嵌套值從 json 文件中提取對象(使用 JavaScript)

[英]How do I extract an object from a json file based on a nested value (using JavaScript)

    const data = [
   {0: {id: "1",cat:{string:[{color:"yellow",weight:"10"},{color:"orange",Weight:"10"}]}},
   {1: {id: "1",cat:{string:[{color:"blue",weight:"10"},{color:"orange",Weight:"10"}]}},
   {2: {id: "1",cat:{string:[{color:"white",weight:"10"},{color:"orange",Weight:"10"}]}},
   {3: {id: "1",cat:{string:[{color:"blue",weight:"10"},{color:"orange",Weight:"10"}]}},
]

按顏色過濾:“黃色”

期望輸出: [{0: {id: 1, country: "SA", address: "IOXX",cat:[{color: "yellow",weight: "10"}]}}]

您可以映射您的data數組並檢查每個對象是否通過您的條件。

const data = [
 {0: {id: 1, country: "SA", address: "IOXX",cat:[{color: "yellow",weight: "10"}]}},
 {1: {id:2, country: "SAP", name: "N", address: "IOP",cat:[{color: "blue",weight: "10"}]}},
 {2: {id:3, country: "S", name: "NO", address: "I",cat:[{color: "blue",weight: "10"}]}},
 {3: {id:4, country: "SXX", name: "NOI", address: "INDIA",cat:[{color: "blue",weight: "12"}]}},
]

const filterByColor = function (color) {
  const filteredCats = []
  data.forEach((item, index) => {
    const hasCorrectColor = item[index].cat.every((cat) => cat.color === color)
    if (hasCorrectColor) {
       filteredCats.push(item)
    }
      
  })
  return filteredCats
}

filterByColor('yellow')

您可以使用filter()方法

 const data = [ { 0: { id: "1", cat: { string: [{ color: "yellow", weight: "10" }, { color: "orange", Weight: "10" }] } } }, { 1: { id: "1", cat: { string: [{ color: "blue", weight: "10" }, { color: "orange", Weight: "10" }] } } }, { 2: { id: "1", cat: { string: [{ color: "white", weight: "10" }, { color: "orange", Weight: "10" }] } } }, { 3: { id: "1", cat: { string: [{ color: "blue", weight: "10" }, { color: "orange", Weight: "10" }] } } } ]; var res = data.filter((el, i) => data[i][i]['cat']['string'][0]['color'] === 'yellow'); console.log(res);

暫無
暫無

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

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