本文介绍了平面阵列到多维数组(JavaScript)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数组:

var sampleArray = [
  "CONTAINER",
  "BODY",
  "NEWS",
  "TITLE"];

我希望得到以下输出:

var desiredOutput = [{
        "CONTAINER": [{
            "BODY": [{
                "NEWS": [{
                    "TITLE": []
                }]
            }]
        }]
    }];

如何在JavaScript中实现这一目标?

How can I achieve this in JavaScript?

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

Already tried with recursive loop, but it does not work, gives me undefined.

    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]]);
        }
    }

谢谢

推荐答案

这样做:

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);

{[key]:next} 是相对较新的语法。他们是 。

{[key]: next} is relatively new syntax. They're computed property names.

这个:

const a = 'foo';
const b = {[a]: 'bar'};

类似于:

const a = 'foo';
const b = {};
b[a] = 'bar';






可以重新开始 - 将 forEach 写成一行:


You could re-write the forEach as a one-liner:

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

sampleArray.forEach(key => current.push({[key]: current = [] }));

console.log(data);

这个 current.push 有点反作用 - 直观地说:

This current.push works a little counter-intuitively:


  1. 构造一个要推送的新元素。这会为当前分配一个新值。

  2. 将新元素推送到引用 .push 被调用。


    • 该参考值当前 之前 current = []

  1. Construct a new element to push. This assigns a new value to current.
  2. Push the new element to the reference .push was called on.
    • That reference is the value of current before current = [].

这篇关于平面阵列到多维数组(JavaScript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 22:42