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

时间:2019-10-10 11:03:20

标签: javascript arrays typescript

我需要从给定的ID的嵌套对象数组中获取数据。

我一直在尝试从中获取数据,以便可以将其传递到Angular Gridster 2,但是即使使用array.filter,我仍在努力获得所需的结果。

我以以下数据开头:

[
  {
    "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"
  }

]

我有一个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
  }
]

1 个答案:

答案 0 :(得分:2)

使用Array.prototype.find可以轻松找到所需的元素(授予它只会返回找到的第一个条目,因此,如果您的ID可能是非唯一的,则应该使用过滤器),然后从找到的对象中删除ID,并将其余数据转换为所需的格式。

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);