-3

How to parse an array of objects, so I would end up with an array of all elements containing 'text' of 'ild'.

Here is a sample array:

public data: any[] = [
  {
    treeViewKey:0,
    id: 1,
    text: 'Root Node 1'
  }, {
    treeViewKey:1,
    id: 2,
    text: 'Root Node 2'
  }, {
    treeViewKey:1_0,
    id: 3,
    parentId: 2,
    text: 'Child node of Root Node 2'
  }, {
    treeViewKey:1_1,
    id: 4,
    parentId: 2,
    text: 'Child node of Root Node 2'
  }, {
    treeViewKey:1_2_0,
    id: 5,
    parentId: 4,
    text: 'Child node of Root Node 2'
  }
];

I should end up with 3 elements. What would be the best method to achieve that in javascript or typescript?

The final result should be:

      [
    {
    treeViewKey:1_0,
    id: 3,
    parentId: 2,
    text: 'Child node of Root Node 2'
  }, {
    treeViewKey:1_1,
    id: 4,
    parentId: 2,
    text: 'Child node of Root Node 2'
  }, {
    treeViewKey:1_2_0,
    id: 5,
    parentId: 4,
    text: 'Child node of Root Node 2'
  }
]
lucas
  • 4,445
  • 6
  • 28
  • 48

2 Answers2

3

If you are looking for all the children, you have a better property to get them.

That's the parentId. If the parentId is specified, then they are children.

So filter the data input looking for the ones with parentId property specified.

Below there is also the case looking for 'ild' in text as you asked.

const data = [
  {
    treeViewKey:0,
    id: 1,
    text: 'Root Node 1'
  }, 
  {
    treeViewKey:1,
    id: 2,
    text: 'Root Node 2'
  }, 
  {
    treeViewKey:'1_0',
    id: 3,
    parentId: 2,
    text: 'Child node of Root Node 2'
  }, {
    treeViewKey:'1_1',
    id: 4,
    parentId: 2,
    text: 'Child node of Root Node 2'
  }, {
    treeViewKey:'1_2_0',
    id: 5,
    parentId: 4,
    text: 'Child node of Root Node 2'
  }
];

// filter the elements with parentId property
console.log(data.filter(el => el.parentId));
// filter the elements with 'ild' string in text property
console.log(data.filter(el => el.text.includes('ild')));
quirimmo
  • 9,800
  • 3
  • 30
  • 45
0

Something like:

const elements = data.filter(item => item.parentId);
Jakob E
  • 4,476
  • 1
  • 18
  • 21