平面阵列到多维数组(JavaScript)

and*_*a23 11 javascript arrays object

我有以下数组:

var sampleArray = [
  "CONTAINER",
  "BODY",
  "NEWS",
  "TITLE"];
Run Code Online (Sandbox Code Playgroud)

我想要以下输出:

var desiredOutput = [{
        "CONTAINER": [{
            "BODY": [{
                "NEWS": [{
                    "TITLE": []
                }]
            }]
        }]
    }];
Run Code Online (Sandbox Code Playgroud)

我怎样才能在JavaScript中实现这一目标?

已经尝试过递归循环,但它不起作用,给我未定义.

    dataChange(sampleArray);
    function dataChange(data) {
        for (var i = 0; i < data.length; i++) {
            changeTheArray[data[i]] = data[i + 1];
            data.splice(i, 1);
            dataChange(changeTheArray[data[i]]);
        }
    }
Run Code Online (Sandbox Code Playgroud)

谢谢

Aln*_*tak 9

这就是你要求的,在一行中,没有其他变量:

let desiredOutput = sampleArray.reduceRight((obj, key) => [ { [key]: obj } ], []);
Run Code Online (Sandbox Code Playgroud)

从数组的右端开始,reduceRight调用逐步累积当前数据(以初始值为止[])作为新对象{ [key] : _value_ }中单个键的值,其中该对象本身是数组中的单个条目[ ... ].

  • 好巫术...我试图建立一个`reduce`方法,但由于累加器向下移动而无法使它工作......"反向"是一个聪明的触摸:D (2认同)

Cer*_*rus 3

这将做到这一点:

const sampleArray = ["CONTAINER", "BODY", "NEWS", "TITLE"];
const data = [];    // Starting element.
let current = data; // Pointer to the current element in the loop

sampleArray.forEach(key => {     // For every entry, named `key` in `sampleArray`,
    const next = [];             // New array
    current.push({[key]: next}); // Add `{key: []}` to the current array,
    current = next;              // Move the pointer to the array we just added.
});

console.log(data);
Run Code Online (Sandbox Code Playgroud)

{[key]: next}是相对较新的语法。它们是计算出的属性名称

这:

const a = 'foo';
const b = {[a]: 'bar'};
Run Code Online (Sandbox Code Playgroud)

类似于:

const a = 'foo';
const b = {};
b[a] = 'bar';
Run Code Online (Sandbox Code Playgroud)

可以将其重写forEach为一行:

const a = 'foo';
const b = {[a]: 'bar'};
Run Code Online (Sandbox Code Playgroud)

current.push有点违反直觉:

  1. 构造一个要推送的新元素。这会为 分配一个新值current
  2. 将新元素推送到调用的引用 .push
    • current 该引用就是before 的值current = []