将未知长度的数组减少为嵌套对象

dav*_*ior 1 javascript

我正在尝试获取一个数组并从中创建一个嵌套对象,其中数组中的每个项目都是前一项的属性.

我认为reduce是这样做的方法,但我发现reduce很难掌握,我尝试的一切都让我知道如何进入下一个级别. JS:将数组减少到嵌套对象是一个类似的问题,但我仍然无法尝试它已经尝试了很多变化.

const myArray = ['one', 'two', 'three'];

// Intended Output (note, the staticCount is always 1)
{
    one: {
        staticCount: 1,

        two: {
            staticCount: 1,

            three: {
                staticCount: 1
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Tex*_*Tex 5

一些工作要求Array.prototype.reduceRight:

const myArray = ['one', 'two', 'three']

const nestNode = (acc, key) => {
  acc.staticCount = 1
  return { [key]: acc }
}
console.log(myArray.reduceRight(nestNode, {}))
Run Code Online (Sandbox Code Playgroud)

我们来看看reduceRight(以及扩展名reduce):

我将迭代器函数定义从调用中移出,reduceRight以使示例更容易讨论(请参阅参考资料nestNode).

reducereduceRight类似的:

  1. 每个都有两个参数,一个迭代器函数和该函数的累加器的初始值.第二个参数是可选的,但我会在这里忽略它.

  2. 每个迭代遍历调用它们的数组中的所有项,使用四个参数调用数组中每个项的迭代器函数,累加器,数组中的当前项,当前迭代计数和整个数组你打电话给谁reduce.最后两个参数在这里不相关(我很少使用它们).

  3. 第一次调用迭代器函数时,它将传递给您提供的第二个参数reducereduceRight(初始累加器值).之后,它将传递上一步中迭代器函数返回的任何内容.

因为我认为reduce(并且通过扩展reduceRight)是值得理解的强大抽象,我将逐步完成代码示例中的前两个步骤:

  1. 在迭代的第一步,我们的迭代器函数被调用如下:nestNode(acc = {}, key = 'three').在里面nestNode,我们添加一个staticCount属性acc并将其设置为1,给予我们acc = { staticCount: 1 }.然后我们创建并返回一个新对象,其属性名为'three'value,其值等于acc.nestNode第一步返回的值是{ three: { staticCount: 1 } },并将在第二步中nestNode使用此值调用.

  2. 在迭代的第二步,我们的迭代器函数被调用如下:nestNode(acc = { three: { staticCount: 1 } }, key = 'two').再次,我们添加一个staticCount属性acc并将其设置为1,给予我们acc = { three: { staticCount: 1 }, staticCount: 1 }.然后,我们创建并返回一个新对象,其属性名为'two'value,其值等于acc.我们返回的价值是{ two: { three: { staticCount: 1 }, staticCount: 1 } }.同样,该值将在下一步中使用.

我将跳过最后一步,因为我希望详细了解前两个步骤足以清除一些问题.如果您有其他问题或仍然发现不清楚或令人困惑的事情,请告诉我.

reduce(和reduceRight)是功能强大,灵活的工具,值得学习和适应.

作为尾声,我会在每一步之后给你留下迭代器函数的返回值:

  1. { three: { staticCount: 1 } }

  2. { two: { three: { staticCount: 1 } }, staticCount: 1 }

  3. { one: { two: { three: { staticCount: 1 } }, staticCount: 1 }, staticCount: 1 }