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"}]}},
]
按顏色過濾:“黃色”
期望輸出: [{0: {id: 1, country: "SA", address: "IOXX",cat:[{color: "yellow",weight: "10"}]}}]
uj5u.com熱心網友回復:
您可以映射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')
uj5u.com熱心網友回復:
你可以使用filter()方法
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" }] } },
];
var res = data.filter((el, i) => data[i][i]['cat'][0]['color'] === 'yellow');
console.log(res);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/353757.html
標籤:javascript 目的 筛选 嵌套 返回
上一篇:每秒從api獲取資料
