Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // The arrays:
- const data = [{
- id: 1,
- name: 'package1',
- rows: [{
- id: 2,
- name: 'item2',
- rows: [{
- id: 3,
- name: 'item 3',
- rows: [{
- id: 4,
- name: 'item 4',
- },
- {
- id: 5,
- name: 'item 5',
- }
- ]
- },
- {
- id: 6,
- name: 'item 6',
- }
- ]
- }]
- },
- {
- id: 7,
- name: 'item 7',
- },
- ];
- const data_with_groups = [{
- id: 'g1',
- name: 'group1',
- rows: [{
- id: 1,
- name: 'package1',
- rows: [{
- id: 2,
- name: 'slot 99',
- rows: [{
- id: 3,
- name: 'item 2',
- rows: [{
- id: 4,
- name: 'item 7',
- },
- {
- id: 5,
- name: 'item 9',
- }
- ]
- },
- {
- id: 6,
- name: 'item 3',
- }
- ]
- }]
- },
- {
- id: 7,
- name: 'item 0',
- },
- ]
- },
- {
- id: 'g2',
- name: 'group2',
- rows: []
- }
- ];
- function find( id, rows, parent_item ) {
- for ( let [index, item] of rows.entries() ) {
- if ( id === item.id )
- return parent_item;
- if ( 'rows' in item )
- return find( id, item.rows, item );
- };
- }
- console.log( find(3, data).id ); // 2
- console.log( find(5, data_with_groups).id ); // 3
- console.log( find(7, data_with_groups) ); // undefined, because there is no parent object
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement