我有以下格式的数据:
要素1:“欧洲>德国>柏林>主办事处”(反对)
要素2:“美利坚合众国>美国>总部”(反对)
要素3:“美国>美国>纽约>主要办公室”(对象)
要素4:"America > United States > NY > Sub Office“(Object)
要素5:“联合王国>英格兰>伦敦>主办事处”(对象)
首先,我尝试根据">“字符拆分数组,并以以下格式创建一个包含所有元素的树(vanilla /es6):
"Europe": {
"Germany": {
"Berlin": {
"Main Office": "Object"
}
}
},我的尝试:
Array.prototype.slice.call(elements).forEach((el) => {
let
stringIHave = el.name, // "Europe > Germany > Berlin > Main Office"
keywordsArr = stringIHave.split( " > " ),
arrayTree = new Array();
Array.prototype.slice.call(keywordsArr).forEach((subEl) => {
//arrayTree.push(el.toString()); // Result: {"Europe", "Germany", "Berlin", "Main Office" }
// What I'm Seeking:
// "Europe": { "Germany": { "Berlin": { "Main Office": "Object" } } },
});
});数据格式化后,我们需要找到所有数组的联合(或一个数组),如下所示:
[
"Europe": {
"Germany": {
"Berlin": {
"Main Office": "Object"
}
}
},
"America": {
"United States": {
"Headquarters",
"NY": {
"Main Office": "Object",
"Sub Office": "Object"
}
}
},
"United Kingdom": {
"England": {
"London": {
"Main Office": "Object"
}
}
}
]我一直试图使用Array.from(new Set(masterArray))来查找所有数组的联合,但没有骰子!
发布于 2020-02-14 17:19:14
可以对数组中的每个字符串使用递归函数来构造嵌套对象。
const data = [
'Element 1: Europe > Germany > Berlin > Main Office',
'Element 2: America > United States > Headquarters',
'Element 3: America > United States > NY > Main Office',
'Element 4: America > United States > NY > Sub Office',
'Element 5: United Kingdom > England > London > Main Office'
]
//remove the string before ':' on all array elements.
let data1 = data.map(str => str.slice( str.indexOf(':') +1, -1 ));
let arrayTree = data1.map(str => convertToTree(str)) ;
console.log(arrayTree);
function convertToTree(str) {
let places = str.split('>');
if(places.length === 1) {
return ({"Main Office": "Object"});
}
//the first part of the splited string should be the property and the remaining part will be converted
//back to string and sent to the recursive function until the result of the split becomes a single element
return ({ [places[0]]:convertToTree(places.slice(1).join('>')) });
}
https://stackoverflow.com/questions/60229843
复制相似问题