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)
谢谢
这就是你要求的,在一行中,没有其他变量:
let desiredOutput = sampleArray.reduceRight((obj, key) => [ { [key]: obj } ], []);
Run Code Online (Sandbox Code Playgroud)
从数组的右端开始,该reduceRight调用逐步累积当前数据(以初始值为止[])作为新对象{ [key] : _value_ }中单个键的值,其中该对象本身是数组中的单个条目[ ... ].
这将做到这一点:
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有点违反直觉:
current。.push。
current 该引用就是before 的值current = []。| 归档时间: |
|
| 查看次数: |
468 次 |
| 最近记录: |