首页 > 解决方案 > Javascript获取嵌套对象的完整索引

问题描述

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' }
]

我想要的如下所示,

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'

我已经为此挣扎了太多时间,但我无法做到。我想我应该堆叠每个parent索引,但我不知道如何获取它的父级。有没有办法做到这一点?

不解析id字符串。每个 id 都有随机字符串。id likeitem1-2是为了便于演示。

我认为我的方式太冗长了...我尝试过...

// 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('-')

标签: javascript

解决方案


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' }
];

const searchIt = (node, search, path = '', position = 0) => {
  if (node.id && node.id === search) {return path !== '' ? `${path}-${position}` : position;}
  if (!node.children) {return false}
  const index = node.children.findIndex((x) => x.id && x.id === search);
  if (index >= 0) {
    return path !== '' ? `${path}-${index + 1}` : index + 1;
  }
  for (let i = 0; i < node.children.length; i++) {
    const result = searchIt(node.children[i], search, path !== '' ? `${path}-${i+1}` : i + 1, i);
    if (result){
      return result;
    }
  }
  return false;
};

console.log(searchIt({children: items}, 'item1-1'));
console.log(searchIt({children: items}, 'item1-1-1'));
console.log(searchIt({children: items}, 'item1-1-2'));
console.log(searchIt({children: items}, 'item1-1-3'));
console.log(searchIt({children: items}, 'item1-1-3-1'));
console.log(searchIt({children: items}, 'item1-2-1'));
console.log(searchIt({children: items}, 'item1-1-3-2'));
console.log(searchIt({children: items}, 'item1-2-2'));
console.log(searchIt({children: items}, 'item3'));

推荐阅读