简体   繁体   English

使用给定 ID 的对象过滤嵌套数组

[英]Filter nested array with objects given a certain ID

I need to get data from a nested array of objects, given an ID that I have.给定我拥有的 ID,我需要从嵌套的对象数组中获取数据。

I have been trying to get data from it so that I can pass it in to Angular Gridster 2, but even when using array.filter, I am struggling to get the results I want.我一直在尝试从中获取数据,以便将其传递给 Angular Gridster 2,但即使使用 array.filter,我也很难得到我想要的结果。

Data I start with:我开始的数据:

[
  {
    "0": {
      "cols": 15,
      "id": "5-1564645705217",
      "rows": 7,
      "type": 0,
      "x": 0,
      "y": 0
    },
    "1": {
      "cols": 15,
      "id": "5-1564645705217",
      "rows": 7,
      "type": 1,
      "x": 15,
      "y": 0
    },
    "2": {
      "cols": 15,
      "id": "5-1564645705217",
      "rows": 8,
      "type": 2,
      "x": 0,
      "y": 7
    },
    "id": "1zk66HvI97C03751LNQm"
  },
  {
    "0": {
      "cols": 5,
      "id": "5-1564545",
      "rows": 7,
      "type": 0,
      "x": 0,
      "y": 0
    },
    "1": {
      "cols": 5,
      "id": "5-1564545",
      "rows": 7,
     "type": 1,
      "x": 15,
      "y": 0
    },
    "id": "8gdfg897C03751LNQm"
  }

]

I have an id (such as 1zk66HvI97C03751LNQm) and want to be able to fetch the contents so that I end up with:我有一个 id(例如 1zk66HvI97C03751LNQm)并且希望能够获取内容,以便最终得到:

[
  {
    "cols": 15,
    "id": "5-1564645705217",
    "rows": 7,
    "type": 0,
    "x": 0,
    "y": 0
  },
  {
    "cols": 15,
    "id": "5-1564645705217",
    "rows": 7,
    "type": 1,
    "x": 15,
    "y": 0
  },
  {
    "cols": 15,
    "id": "5-1564645705217",
    "rows": 8,
    "type": 2,
    "x": 0,
    "y": 7
  }
]

Using Array.prototype.find you can easily locate element you want (granted it will only return first found entry, so if your id can be non unique you should use filter instead) after which i remove id from the found object, and turn the rest of the data into desired format.使用Array.prototype.find你可以很容易地找到你想要的元素(它只会返回第一个找到的条目,所以如果你的 id 可以是非唯一的,你应该使用 filter 代替),然后我从找到的 object 中删除 id,然后转动rest 将数据转换成所需格式。

 const data = [{"0": {"cols": 15, "id": "5-1564645705217", "rows": 7, "type": 0, "x": 0, "y": 0}, "1": {"cols": 15, "id": "5-1564645705217", "rows": 7, "type": 1, "x": 15, "y": 0}, "2": {"cols": 15, "id": "5-1564645705217", "rows": 8, "type": 2, "x": 0, "y": 7}, "id": "1zk66HvI97C03751LNQm"}, {"0": {"cols": 5, "id": "5-1564545", "rows": 7, "type": 0, "x": 0, "y": 0}, "1": {"cols": 5, "id": "5-1564545", "rows": 7, "type": 1, "x": 15, "y": 0}, "id": "8gdfg897C03751LNQm"}] const searchId = "1zk66HvI97C03751LNQm"; const {id, ...elementFound} = data.find(({id})=> id === searchId) || {}; // skip id as unnecessary, return empty object in case of no entries matching search criteria const elementParsed = Object.values(elementFound); // get values of other fields console.log(elementParsed);

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

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