-
largeQ
您可以通过组合reduce和来实现这一点filtervar 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)
-
沧海一幻觉
有很多方法可以做到这一点,一种是将顶级数组映射到子数组过滤结果,然后对其进行过滤: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()))], []);
-
智慧大石
您的数据集是一个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);
-
LEATH
请在下面找到代码来过滤掉里面的值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);