我有以下数组:
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]]);
}
}
由于
答案 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
有点违反直觉:
current
。.push
被调用。
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);