I have this array in typescript: [{ group: 'Bachlor', items: [ { id: 11, name: '11g' },…
- User
I have this array in typescript: [{ group: 'Bachlor', items: [ { id: 11, name: '11g' }, { id: 12, name: '12g' }, { id: 13, name: '13g' } ] } { group: 'Maga', items: [ { id: 14, name: '14g' }, { id: 15, name: '15g' }, { id: 16, name: '16g' } ] }] I need to find id of element wich has name 15g
- Assistant
To find the ID of the element with the name '15g' from your array, you can use a combination of the
findandfindItemmethods in TypeScript. Given your array structure, you should first iterate through the array to access each group. Then, check theitemsarray in each group for the item with the name '15g'. Here's how you could do it:const data = [ { group: 'Bachlor', items: [ { id: 11, name: '11g' }, { id: 12, name: '12g' }, { id: 13, name: '13g' } ] }, { group: 'Maga', items: [ { id: 14, name: '14g' }, { id: 15, name: '15g' }, { id: 16, name: '16g' } ] } ]; function findItemIdByName(groups: any[], name: string): number | undefined { for (const group of groups) { const itemFound = group.items.find((item: any) => item.name === name); if (itemFound) { return itemFound.id; } } // Return undefined if no item with the specified name is found return undefined; } const itemId = findItemIdByName(data, '15g'); console.log(itemId); // Should log: 15