简体   繁体   English

使用JS在二维或多维数组中按键过滤

[英]Filter by key in 2d or multidimensional array using JS

I am tyring to filter by a particualar key in my array that is nested inside a multi arrary.我很想通过嵌套在多数组中的数组中的特定键进行过滤。 I keep getting returned my filter is not a function.我不断收到退货,我的过滤器不是 function。 I am trying to return only the array that has the object key "assets"我试图只返回具有 object 键“资产”的数组

My Data Array:我的数据数组:

const variableOpts = [
   [
      {
         "assets":"EP009285440323",
         "rootId":"21253358",
      },
      {
         "assets":"EP009285440323",
         "rootId":"21253358",
      },
      {
         "assets":"EP009285440323",
         "rootId":"21253358",
      }
   ],
   [
      {
         "TMSId":"EP035579760050",
         "rootId":"21253391",
      },
      {
         "TMSId":"EP035579760050",
         "rootId":"21253391",
      },
      {
         "TMSId":"EP035579760050",
         "rootId":"21253391",
      }
   ],
   [
      {
         "TMSId":"EP033168400060",
         "rootId":"21166708",
      },
      {
         "TMSId":"EP033168400060",
         "rootId":"21166708",
      },
      {
         "TMSId":"EP033168400060",
         "rootId":"21166708",
      }
   ]
]

JS: JS:

const filResults = variableOpts.map((el) => {
      return el.map((prg) => prg.filter((obj) => obj.includes("assets")));
    });
    console.log("filData", filResults); <---Uncaught TypeError: prg.filter is not a function"

Desired Output:所需的 Output:

[
      {
         "assets":"EP009285440323",
         "rootId":"21253358",
      },
      {
         "assets":"EP009285440323",
         "rootId":"21253358",
      },
      {
         "assets":"EP009285440323",
         "rootId":"21253358",
      }
   ],

By having only one array which onbjects contains properties assets , you could find the array by looking into the nested array for the wanted property.通过只有一个 onbjects 包含属性assets的数组,您可以通过查看所需属性的嵌套数组来找到该数组。

 const variableOpts = [[{ assets: "EP009285440323", rootId: "21253358" }, { assets: "EP009285440323", rootId: "21253358" }, { assets: "EP009285440323", rootId: "21253358" }], [{ TMSId: "EP035579760050", rootId: "21253391" }, { TMSId: "EP035579760050", rootId: "21253391" }, { TMSId: "EP035579760050", rootId: "21253391" }], [{ TMSId: "EP033168400060", rootId: "21166708"}, { TMSId: "EP033168400060", rootId: "21166708" }, { TMSId: "EP033168400060", rootId: "21166708" }]], result = variableOpts.find(a => a.some(o => 'assets' in o)); console.log(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM