首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JS拆分数组以生成子数组并找到所有数组的联合集。

JS拆分数组以生成子数组并找到所有数组的联合集。
EN

Stack Overflow用户
提问于 2020-02-14 16:09:20
回答 1查看 207关注 0票数 0

我有以下格式的数据:

要素1:“欧洲>德国>柏林>主办事处”(反对)

要素2:“美利坚合众国>美国>总部”(反对)

要素3:“美国>美国>纽约>主要办公室”(对象)

要素4:"America > United States > NY > Sub Office“(Object)

要素5:“联合王国>英格兰>伦敦>主办事处”(对象)

首先,我尝试根据">“字符拆分数组,并以以下格式创建一个包含所有元素的树(vanilla /es6):

代码语言:javascript
复制
"Europe": {
  "Germany": {
    "Berlin": {
      "Main Office": "Object"
    }
  }
},

我的尝试:

代码语言:javascript
复制
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" } } },

    });

});

数据格式化后,我们需要找到所有数组的联合(或一个数组),如下所示:

代码语言:javascript
复制
[
"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))来查找所有数组的联合,但没有骰子!

EN

回答 1

Stack Overflow用户

发布于 2020-02-14 17:19:14

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

代码语言:javascript
复制
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('>'))  });
 }

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60229843

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档