我有以下对象:

const obj = {
  alphas: {
    top: [{name: "q"}, {name: "w"}],
    middle: [{name: "a"}, {name: "s"}],
    bottom: [{name: "z"}, {name: "x"}],
  },
  numbers: {
    low: [{name: "1"}, {name: "2"}, {name: "3"}],
    high: [{name: "1000"}, {name: "2000"}],
  }
}


我需要name的嵌套索引。
例如,如果我要查找"s",则结果应为数组[0, 1]


0因为"s"在第一类(alphas
1,因为"s"在第二个子类别(middle)中。


我可以在单独的循环中找到索引:

const categoryIndex = Object.keys(obj).findIndex(
  cat => Object.keys(obj[cat]).some(
    subcat => obj[cat][subcat].some(
      key => key.name === "s")));

const categoryName = Object.keys(obj)[categoryIndex];
const subcategoryIndex = Object.keys(obj[categoryName]).findIndex(
  subcat => obj[categoryName][subcat].some(key => key.name === "s"));

const result = [categoryIndex, subcategoryIndex];


https://jsfiddle.net/7w523ojn/

有两个单独的循环可能会花费太多,因此我正在寻找一种立即获取索引的方法。像这样:

[categoryIndex , subcategoryIndex] = ...


有没有办法一次获取嵌套索引?
也欢迎涉及LodashRamda和诸如此类的解决方案。
谢谢。

最佳答案

如果我正确理解您的问题,则可以通过递归搜索和返回函数来实现,如下所示:



const obj={alphas:{top:[{name:"q"},{name:"w"}],middle:[{name:"a"},{name:"s"}],bottom:[{name:"z"},{name:"x"}]},numbers:{low:[{name:"1"},{name:"2"},{name:"3"}],high:[{name:"1000"},{name:"2000"}]}};

const recursiveSearch = (object, searchFor) => {

  let index = 0;
  for (const key in object) {
    const value = object[key];

    if (Array.isArray(value)) {

      /* If object value is an array, iterate through it and
      search for item with name field matching searchFor
      character */
      const array = value;
      for (let i = 0; i < array.length; i++) {

        /* If array item's name matches searchFor charater
        then return this as the first entry in our results
        array */
        if (array[i].name === searchFor) {
          return [index, i];
        }
      }
    } else if (typeof object === "object") {

      /* If object value is object, then recursivly search
      through children for a result. If an result is found,
      prepend the current key's index to the result array */
      const result = recursiveSearch(value, searchFor);

      /* Array.isArray() tells us this call to recursiveSearch()
      found a result, so we are to return from this call */
      if (Array.isArray(result)) {
        return [index].concat(result);
      }
    }

    index++;
  }
};

console.log('indicies for "s":', recursiveSearch(obj, 's'));

10-05 20:33
查看更多