looking for some solutions? You are welcome.

SOLVED: Javascript get full index of nested object

Juntae:
const items = [
   { id: 'item1',
     children: [ 
      { id: 'item1-1',
        children: [
          { id: 'item1-1-1' },
          { id: 'item1-1-2' },
          { id: 'item1-1-3'
            children: [
               { id: 'item1-1-3-1'}
            ]
          },
        ]
      },
      { id: 'item1-2',
        children: [
          { id: 'item1-2-1' }
        ]
      }
    ]
   },
   { id: 'item2' }
]

What I want to is like below,

function getFullDepthOfObject(){
  ...
}

getFullIndexOfObject('item1') =====> return '1'
getFullIndexOfObject('item1-2') =====> return '1-2'
getFullIndexOfObject('item1-1-1') =====> return '1-1-1'
getFullIndexOfObject('item1-1-2') =====> return '1-1-2'
getFullIndexOfObject('item2') ===> return '2'

I have struggled with this too much time, But I couldn't make it. I think I should stack each of parent index, But I don't know how to get its parent. Is there a way to do this?

Not parse of id string. Each id has randomic string. The id like item1-2 is for easier demonstration.

I think my way is too verbose... I tried like ...

// Get Full Index of item1-1


// First, get the target's depth.
var depth = 0;

function getDepthOfId(object, id) {
    var level;
    if (object.id === id) return 1;
    object.children && object.children.some(o => level = getDepthOfId(o, id));
    return level && level + 1;
}

depth = getDepthOfId(items[0], 'item1-1');
console.log('depth === ', depth)


// Then, iterate recursively with length of depth.

var indexStacks = [];


function getNestedIndexOfId(obj, id, index) {
    if (obj.id === id) {
        indexStacks = [index, ...indexStacks]
        return index;
    }

    if (obj.children) {
        depth++;
        obj.children.map((child, i) => {
            getNestedIndexOfId(child, id, i)
        })
    }
}

// I can get the inner index, but I can't get its parent id.
// I don't know how to this..

function getParentId(obj, id){
    // ...?
    var parentId;
    return parentId;
}

for(var i=0; i<depth; i++){
        getNestedIndexOfId('...')
}


// full path will be 
indexStacks.join('-')



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
Share:

No comments:

Recent