我有以下数组:
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]]);
}
}
谢谢
这样做:
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}
是相对较新的语法。他们是 计算属性名称。
这个:
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 = []
。
这样做:
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}
是相对较新的语法。他们是 计算属性名称。
这个:
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 = []
。
这就是你要求的,在一行中,没有其他变量:
let desiredOutput = sampleArray.reduceRight((obj, key) => [ { [key]: obj } ], []);
该 reduceRight
呼叫, 从数组的右端开始,逐步累积当前数据(以初始值为种子) []
)作为新对象中单个键的值 { [key] : _value_ }
其中该对象本身是数组中的单个条目 [ ... ]
。
嗨,我做了一点 演示 :
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);