javascript—构建一个“针”数组以访问嵌套数组中的值的函数?

xoshrz7s  于 2021-09-08  发布在  Java
关注(0)|答案(3)|浏览(312)

我有一个嵌套数组,其中包含多个不同级别的字符串。

let nested = [
  "ONE",
  [
    "TWO",
    "THREE",
    [
      "FOUR",
      "FIVE"
    ],
    "SIX",
    "SEVEN"
  ],
  [
    "HEIGHT"
  ],
  "NINE"
]

我有一个工作函数,可以遍历我的嵌套数组来检索值,使用索引数组作为“指针”:

const getValueByIndexes = (array,indexes) => {
  const children = array[indexes[0]];

  if(indexes.length > 1){
    return getValueByIndexes(children,indexes.slice(1));
  }else{
    return children;
  }
}

let test = getValueByIndexes(nested,[1,2,1]);

console.log(test); //this IS returning "FIVE", as expected

这很有效;但我的问题是,我需要一个函数来构建这些针;基于我的嵌套数组。
我想要的输出是:

[
  [0],//ONE
  [1,0],//TWO
  [1,1],//THREE
  [1,2,0],//FOUR
  [1,2,1],//FIVE
  [1,3],//SIX
  [1,4],//SEVEN
  [2,0],//HEIGHT
  [3],//NINE
]

我怎样才能做到这一点?谢谢

zzoitvuj

zzoitvuj1#

您可以通过检查数组来采用递归方法。

const
    getIndices = array => array.flatMap((v, i) => Array.isArray(v)
        ? getIndices(v).map(a => [i, ...a])
        : [[i]]
    ),
    data = ["ONE", ["TWO", "THREE", ["FOUR", "FIVE"], "SIX", "SEVEN"], ["HEIGHT"], "NINE"],
    result = getIndices(data); 

result.forEach(a => console.log(...a));
.as-console-wrapper { max-height: 100% !important; top: 0; }
oewdyzsn

oewdyzsn2#

还可以使用递归生成器函数:

function* build_arr(d, c = []){
    for (var i = 0; i < d.length; i++){
        yield* (!Array.isArray(d[i]) ? [[...c, i]] : build_arr(d[i], [...c, i]))
    }
}
let nested = ['ONE', ['TWO', 'THREE', ['FOUR', 'FIVE'], 'SIX', 'SEVEN'], ['HEIGHT'], 'NINE']
console.log(Array.from(build_arr(nested)))
snz8szmq

snz8szmq3#

nina scholz和ajax1234的回答都很好。但用一种更通用的方法来处理任意对象及其路径也不难。以下是我经常使用的函数:

const getLeafPaths = (obj) =>
  Object (obj) === obj
    ? Object .entries (obj) .flatMap (
        ([k, v]) => getLeafPaths (v) .map (p => [Array .isArray (obj) ? Number(k) : k, ...p])
      )
    : [[]]

let nested = ["ONE", ["TWO", "THREE", ["FOUR", "FIVE"], "SIX", "SEVEN"], ["HEIGHT"], "NINE"]

console .log (getLeafPaths (nested))
//=> [[0], [1, 0], [1, 1], [1, 2, 0], [1, 2, 1], [1, 3], [1, 4], [2, 0], [3]]
.as-console-wrapper {max-height: 100% !important; top: 0}

因此它解决了这个问题,但对其他对象也很有用:

getLeafPaths ({foo: 1, bar: {baz: [{qux: 2}, {quz: 3}], corge: 4}, grault: [5, 6, 7]})

将产生:

[
  ["foo"], 
  ["bar", "baz", 0, "qux"], 
  ["bar", "baz", 1, "quz"], 
  ["bar", "corge"], 
  ["grault", 0], 
  ["grault", 1], 
  ["grault", 2]
]

相关问题