如何在两个深度数组中进行过滤

我想要过滤两个深层数组,实际上是我的 JSON:


{

  "0": {

    "product":[{

      "uuid":"uid",

      "name":"Rice"

    },

    {

      "uuid":"uid",

      "name":"Pasta"

    }]

  },

  "1": {

    "product":[{

      "uuid":"uid",

      "name":"Milk"

    }]

  }

}

当我用“ric”一词进行过滤时,我希望得到类似的结果:


{

  "0": {

    "product":[{

      "uuid":"uid",

      "name":"Rice"

    }]

  }

}

但我得到了这个结果:


{

  "0": {

    "product":[{

      "uuid":"uid",

      "name":"Rice"

    },

    {

      "uuid":"uid",

      "name":"Pasta"

    }]

  }

}

我的代码:


dataSort.categories = json 和 event.target.value.toLowerCase() = 特定单词


dataSort.categories.filter(s => s.products.find(p => p.name.toLowerCase().includes(event.target.value.toLowerCase())));


一只萌萌小番薯
浏览 87回答 4
4回答

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);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript