Javascript 如何基于包含嵌套键的数组生成具有嵌套键的对象';什么是关键地点?

Javascript 如何基于包含嵌套键的数组生成具有嵌套键的对象';什么是关键地点?,javascript,Javascript,我有一个数组,其中包含将对象中的子对象描述为字符串的数组 我无法使用提供的输入生成所需的结果 let obj = {} let arr = [ ["one", "two", "three", "four"], ["one", "two", "three", "four"], ["one", "two", "three", "four", "five"], ["one", "hi"] ] console.log(JSON.stringify(obj, null, 4)) 期望

我有一个数组,其中包含将对象中的子对象描述为字符串的数组

我无法使用提供的输入生成所需的结果

let obj = {}

let arr = [
  ["one", "two", "three", "four"],
  ["one", "two", "three", "four"],
  ["one", "two", "three", "four", "five"],
  ["one", "hi"]
]

console.log(JSON.stringify(obj, null, 4))
期望输出:

let result = {
  one: {
    children: {
      two : {
        children: {
          three: {
            children: {
              four: {
                children: {
                  five: {}
                }
              }
            }
          }
        }
      },
      hi: {}
    }
  }
}

一个选项是将一个
reduce
嵌套在另一个
reduce
中,一个迭代属性数组,另一个迭代每个属性

但是,您必须确保根据属性数组的长度检查属性的索引,因为您不希望为嵌套最深的对象创建
子对象

const arr=[
[“一”、“二”、“三”、“四”],
[“一”、“二”、“三”、“四”],
[“一”、“二”、“三”、“四”、“五”],
[“一”,“你好”]
];
常量输出=arr.reduce((a,propArr)=>{
概率减少((对象、属性、i)=>{
如果(!obj[prop])obj[prop]={};
如果(!obj[prop].children&&i!==propArr.length-1)obj[prop].children={};
返回obj[prop]。子对象;
},a);
返回a;
}, {});
控制台日志(输出)可能重复的