4 回答

TA貢獻2039條經驗 獲得超8個贊
您可以通過組合reduce和來實現這一點filter
var input = {
"0": {
"product":[{
"uuid":"uid",
"name":"Rice"
},
{
"uuid":"uid",
"name":"Pasta"
}]
},
"1": {
"product":[{
"uuid":"uid",
"name":"Milk"
}]
}
}
var search = "ric"
var result = Object.entries(input).reduce( (acc, [key,val]) => {
found = val.product.filter(x => x.name.toLowerCase().includes(search.toLowerCase()))
if(found.length){
acc[key] = {...val, product: found}
}
return acc
},{})
console.log(result)

TA貢獻1824條經驗 獲得超5個贊
有很多方法可以做到這一點,一種是將頂級數組映射到子數組過濾結果,然后對其進行過濾:
dataSort.categories .map(s => s.products.filter(p => p.name.toLowerCase().includes(event.target.value.toLowerCase()))) .filter(s => !!s.products.length);
您可能還更喜歡獲得“平面”數組作為結果,因為在之后使用它更容易:
dataSort.categories .reduce((acc, s) => [...acc, s.products.filter(p => p.name.toLowerCase().includes(event.target.value.toLowerCase()))], []);

TA貢獻1946條經驗 獲得超3個贊
您的數據集是一個Object,而不是一個Array,并且過濾器是一個 Array 方法。您可以通過Object.values循環對象值來使用reduce,然后過濾您的產品數組。
const data = {
? '0': {
? ? product: [
? ? ? {
? ? ? ? uuid: 'uid',
? ? ? ? name: 'Rice',
? ? ? },
? ? ? {
? ? ? ? uuid: 'uid',
? ? ? ? name: 'Pasta',
? ? ? },
? ? ],
? },
? '1': {
? ? product: [
? ? ? {
? ? ? ? uuid: 'uid',
? ? ? ? name: 'Milk',
? ? ? },
? ? ],
? },
};
const keyword = 'ric';
const dataset = Object.values(data);
const results = dataset.reduce((acc, item, index) => {
? const search = keyword.toLowerCase();
? const product = item.product.filter(product => product.name.toLowerCase().includes(search));
? if (product.length) acc[index] = { ...item, product };
? return acc;
}, {});
console.log(results);

TA貢獻1936條經驗 獲得超7個贊
請在下面找到代碼來過濾掉里面的值product.name,并且只返回與數組中的相等條件匹配的值product。
const json = [
{
product: [
{
uuid: "uid",
name: "Rice",
},
{
uuid: "uid",
name: "Pasta",
},
],
},
{
product: [
{
uuid: "uid",
name: "Milk",
},
],
},
];
const inputValue = "rIc";
const filteredArray = [];
json.map((s) => {
const item = s.product.find((p) =>
p.name.toLowerCase().includes(inputValue.toLowerCase())
);
item && filteredArray.push({ product: item });
});
console.dir(filteredArray);
添加回答
舉報