4 回答

TA貢獻(xiàn)2039條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以通過(guò)組合reduce和來(lái)實(shí)現(xiàn)這一點(diǎn)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貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超5個(gè)贊
有很多方法可以做到這一點(diǎn),一種是將頂級(jí)數(shù)組映射到子數(shù)組過(guò)濾結(jié)果,然后對(duì)其進(jìn)行過(guò)濾:
dataSort.categories .map(s => s.products.filter(p => p.name.toLowerCase().includes(event.target.value.toLowerCase()))) .filter(s => !!s.products.length);
您可能還更喜歡獲得“平面”數(shù)組作為結(jié)果,因?yàn)樵谥笫褂盟菀祝?/p>
dataSort.categories .reduce((acc, s) => [...acc, s.products.filter(p => p.name.toLowerCase().includes(event.target.value.toLowerCase()))], []);

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超3個(gè)贊
您的數(shù)據(jù)集是一個(gè)Object,而不是一個(gè)Array,并且過(guò)濾器是一個(gè) Array 方法。您可以通過(guò)Object.values循環(huán)對(duì)象值來(lái)使用reduce,然后過(guò)濾您的產(chǎn)品數(shù)組。
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貢獻(xiàn)1936條經(jīng)驗(yàn) 獲得超7個(gè)贊
請(qǐng)?jiān)谙旅嬲业酱a來(lái)過(guò)濾掉里面的值product.name,并且只返回與數(shù)組中的相等條件匹配的值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);
添加回答
舉報(bào)