使用javascript ES6,我试图获得一个简单的算法来转换包含字符串的数组的简单算法,没有大小限制,因此我需要一个带有数组项目作为标签的对象和子阵列中的每个项目,取决于他的位置,难以解释,
这是我之前“得到的”以及我想要的“之后”。
before = ["a","b","c","d"]
after = {
name: "a"
children: [
{
name: "b",
children: [
{
name: "c",
children: [
name: "d"
]
}
]
}
]
}
感谢您的帮助,我完全被阻止
答案 0 :(得分:2)
您可以使用Array#reduceRight从数组中创建结构。
reduceRight()
从末尾获取一个元素,用对象包装它,并将之前的结果添加到children数组中。这些孩子是使用Object#assign有条件分配的,因为最后一个对象没有孩子。
const before = ["a","b","c","d"];
const after = before.reduceRight((r, name) =>
Object.assign({ name }, r !== null ? { children: [r] } : {}),
null);
console.log(after);

答案 1 :(得分:1)
另一个答案,没有使用那些花哨的const
和reduceRight
的东西! = d
var before = ["a","b","c","d"];
var after = createChildren(before);
console.log(after);
function createChildren(obj) {
if (obj.length) {
return { name: obj.shift(), children: [ createChildren(obj)] };
}
return new Array();
}

更短的版本:
var before = ["a","b","c","d"];
var after = createChildren(before);
console.log(after);
function createChildren(obj) {
return obj.length && { name: obj.shift(), children: [ createChildren(obj)] } ||
new Array();
}

答案 2 :(得分:1)
这是我的解决方案:
const after = ([name, ...rest], children = rest.length && [after(rest)]) =>
children
? { name, children }
: { name };
const before = ['a', 'b', 'c', 'd'];
console.log(JSON.stringify(after(before), null, 2));

答案 3 :(得分:1)
此解决方案类似于Ori Dori的解决方案,但它没有使用Object#assign。
["a","b","c","d"].reduceRight((r, v, i) => {
r.name = v;
return i === 0 ? r : { children: [r] }
}, {});