JS拆分数组以创建子数组并找到所有数组的联合集



我有以下格式的数据:

要点1:"欧洲>德国>柏林>总部"(对象(

构成部分2:"美国>美国>总部"(对象(

要点3:"美国>美国>纽约>总部"(对象(

构成部分4:"美国>美国>纽约>办事分处"(对象(

构成部分5:"联合王国>英格兰>伦敦>总部"(对象(

首先,我尝试根据">"字符拆分数组,并使用以下格式(vanilla js/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))来查找所有数组的联合,但没有骰子!

您可以对数组中的每个字符串使用递归函数来构造嵌套对象。

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('>'))  });
}

相关内容

  • 没有找到相关文章

最新更新