-1

I need to get data from a nested array of objects, given an ID that I have.

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.

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:

[
  {
    "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
  }
]
Peder
  • 53
  • 1
  • 4
  • Possible duplicate of [How do I check if an array includes an object in JavaScript?](https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-an-object-in-javascript) – Jay Oct 10 '19 at 11:16

1 Answers1

2

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.

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);
Krzysztof Krzeszewski
  • 5,912
  • 2
  • 17
  • 30