我在實作嵌套資料過濾時遇到問題。我有來自 API 的這種資料:
const animals = {
bugs: ['ant', 'cricket'],
fish: ['shark', 'whale', 'tuna'],
mammals: ['cow', 'horse', 'sheep'],
birds: ['eagle', 'crow', 'parrot'],
predators: ['tiger', 'lion']
}
我必須用這個陣列過濾它們:
const data = ['shark', 'horse', 'cow', 'parrot']
我想要達到的結果:
const filtered = {
fish: ['shark'],
mammals: ['cow', 'horse'],
birds: ['parrot'],
}
我努力了 :
filter.forEach((item) => {
for (let key in animals) {
let species = []
if (animals[key].includes(item)) {
filtered[key] = [...species, species]
}
}
})
結果:
const filtered = {
fish: ['whale'],
mammals: ['cow',],
birds: ['parrot'],
}
我仍然無法達到預期的結果,因為陣列中的專案不會被添加而是被替換。我被困在這里。任何幫助將不勝感激。謝謝 !
uj5u.com熱心網友回復:
首先,您需要回圈您的物件,然后根據資料過濾動物陣列。
const animals = { fish: ['shark', 'whale', 'tuna'], mammals: ['cow', 'horse', 'sheep'], birds: ['eagle', 'crow', 'parrot'],};
const data = ['shark', 'horse', 'cow', 'parrot'];
let filtered = {};
for (var a of Object.keys(animals)) {
filtered[a] = animals[a].filter(value => data.includes(value));
}
console.log(filtered);
uj5u.com熱心網友回復:
您可以重建物件的條目。
const
animals = { bugs: ['ant', 'cricket'], fish: ['shark', 'whale', 'tuna'], mammals: ['cow', 'horse', 'sheep'], birds: ['eagle', 'crow', 'parrot'], predators: ['tiger', 'lion'] },
data = ['shark', 'horse', 'cow', 'parrot'],
result = Object.fromEntries(Object
.entries(animals)
.flatMap(([k, a]) => {
a = a.filter(v => data.includes(v));
return a.length
? [[k, a]]
: []
})
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
uj5u.com熱心網友回復:
您可以使用以下filter方法:
const fish = animals.fish.filter((animal) => animal === 'shark');
const mammals = animals.mammals.filter((animal) => animal === 'cow' || animal === 'horse');
const birds = animals.birds.filter((animal) => animal === 'parrot');
const filtered = {
fish, // equals to fish: fish
mammals, // equals to mammals: mammals
birds, // equals to birds: birds
};
請注意,這只是一個示例。您可以將自己的檢查放在回呼函式中,但它應該回傳一個布林值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/493204.html
標籤:javascript 数组 目的
