'Search in All' using Linqjs

Asked

Viewed 32 times

3

I’m using the linqJs

When I try to get the id 5512 he returns null, but when I catch the 124, works.

$.Enumerable.From(structure).Where("$.id==5512").ToArray();

Object structure:

[{
    "id": 124,
    "text": "Pai",
    "children": [
      {
        "id": 5511,
        "text": "Filho 1"
      },
      {
        "id": 5512,
        "text": "Filho 2"
      }
    ]
}]

How do I find the ID regardless of the position it is in? In this case the 5512

I guess maybe I could do $.children.id but the array is dynamic so no I have to know the exact position, so I’d like to search at all id

1 answer

3

You cannot access because the item with ID 5512 is on a list within a list, ie when doing .Where("$.id==5512") you are seeking only in the parent elements and not in children.

To do what you want, you can use the .SelectMany() and after that, select by ID. See this example below that I think you will understand better.

var lista = [{
  "id": 124,
  "text": "Pai",
  "children": [{
      "id": 5511,
      "text": "Filho 1"
    },
    {
      "id": 5512,
      "text": "Filho 2"
    }
  ]
}];

var item = Enumerable.From(lista)
                     .SelectMany("$.children")
                     .Where("$.id==5512")
                     .ToArray();

console.log(item);
<script src="https://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.min.js"></script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.