Home > Software engineering >  How to find just first child element in array? Javascript
How to find just first child element in array? Javascript

Time:02-01

I need to find first child element in array and just return it. Here is problem because here is few children elements and i need loop thought each and return every first children element.

Example of array:

let allItems = 
[{  id: 1 , 
    name: 'Test 1' ,
      children: [
       id: 12,
       title: 'Child element'
    ]
},
{  
    id: 2 , 
    name: 'Test 2' 
}, 
{  
    id: 3 , 
    name: 'Test 3',
    children: [
    id: 12,
    title: 'Child element',
       children: [
         id: 123,
         title: 'GRAND Child element',
      ]
    ]
}]

What's the problem here? Since there can be many children elements, do I need to find a parent for each of those elements?

After looping i need array to be:

[{  id: 1 , 
    name: 'Test 1'
},
{  
    id: 2 , 
    name: 'Test 2' 
}, 
{  
    id: 3 , 
    name: 'Test 3'
}]

Wihout children elements.

What I am try:

allItems.map(item => item).filter(filteredItem => !filteredItem.children);

But this is no return me good results

CodePudding user response:

Based on your expected output, here is my solution.

Also note, that you had missing curly braces with your children.

See you modified snippet below:

let allItems = [{
    id: 1,
    name: 'Test 1',
    children: [{
      id: 12,
      title: 'Child element'
    }]
  },
  {
    id: 2,
    name: 'Test 2'
  },
  {
    id: 3,
    name: 'Test 3',
    children: [{
      id: 12,
      title: 'Child element',
      children: [{
        id: 123,
        title: 'GRAND Child element',
      }]
    }]
  }
]

console.log(allItems.map(item => {
  return {
    id: item.id,
    name: item.name
  }
}))

CodePudding user response:

Using map and destructuring is a nice way to achieve what you're looking for

let allItems = [{
    id: 1,
    name: 'Test 1',
    children: [{
      id: 12,
      title: 'Child element'
    }]
  },
  {
    id: 2,
    name: 'Test 2'
  },
  {
    id: 3,
    name: 'Test 3',
    children: [{
      id: 12,
      title: 'Child element',
      children: [{
        id: 123,
        title: 'GRAND Child element',
      }]
    }]
  }
];

const res = allItems.map(x =>  {
  const {id, name} = x;
  return {id, name};
});
console.log(res);

CodePudding user response:

Use these propertys for call first child: .firstchild==>this property calls first Node .firstElementChild==>calls first element

  •  Tags:  
  • Related