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

时间:2017-10-26 09:16:44

标签: javascript arrays object

我有以下数组:

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

我希望得到以下输出:

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

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

由于

3 个答案:

答案 0 :(得分:9)

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

let desiredOutput = sampleArray.reduceRight((obj, key) => [ { [key]: obj } ], []);

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

答案 1 :(得分: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);

{[key]: next}是一种相对较新的语法。他们是computed property names

此:

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

类似于:

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

可以重新编写forEach作为一行代码:

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有点违反直觉:

  1. 构建要推送的新元素。这会为current
  2. 指定一个新值
  3. 将新元素推送到引用 .push被调用。
    • 该引用是<{em> current之前current = [] 的值。

答案 2 :(得分:1)

你好我做了一点demo

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

for(var i = 0; i < sampleArray.length; i++) {
  if(tmp===null){
    generateArray[sampleArray[i]] = {};
    tmp = generateArray[sampleArray[i]];
  }else{
    tmp[sampleArray[i]] = {};
    tmp = tmp[sampleArray[i]];
  }         
}

console.log(generateArray);