简体   繁体   English

如何基于javascript中的字符串数组创建嵌套数组?

[英]How to create nested arrays based on arrays of strings in javascript?

I am trying to create nested arrays with array of strings. 我正在尝试使用字符串数组创建嵌套数组。 Each string object on the array is delimited by a '|' 数组上的每个字符串对象均以'|'分隔 and that char its uses to create a nested array over an already existing array. 该char用于在现有数组上创建嵌套数组。

edit fix IE: current array 编辑修复 IE:当前数组

var arr = [
    { val : 'root|leaf|lead2|boo|foo|lee'},
    { val : 'root|leaf|lead3|boo|foo|lee'},
    { val : 'root|leaf2|boo'},
    { val : 'root|leaf2|foo'},
    { val : 'root|leaf2|leaf3|more'},
    { val : 'root|leaf2|leaf3|things'},
    { val : 'root|leaf2|leaf3|here'},
    { val : 'sibling|leaf|leaf2|boo'},
    { val : 'sibling|leaf|leaf2|foo'},
    { val : 'sibling|leaf|leaf2|lee'},
    { val : 'sibling|boo'},
    { val : 'sibling|foo'},
    { val : 'sibling|boo|leaf3'},
    { val : 'sibling|boo|leaf3|more'},
    { val : 'sibling|boo|leaf3|things'},
    { val : 'sibling|boo|leaf3|here'},
    { val : 'sibling|ops'},
];

var nested = [
    root = [
        leaf = [
            leaf2 = [
                'boo', 'foo', 'lee'
            ],
            leaf3 = [
                'boo', 'foo', 'lee'
            ]
        ], 
        leaf2 = [
            'boo', 'foo', leaf3 = [
                'more', 'things', 'here'
            ]
        ]
    ],
    sibling = [
        leaf = [
            leaf = [
                leaf2 = [
                    'boo', 'foo', 'lee'
                ]
            ]
        ],
        'ops',
        'boo', 'foo', leaf3 = [
            'more', 'things', 'here'
        ]
    ]
];

You can find here a functional approach, by using .map() and .reduce() methods. 通过使用.map().reduce()方法,您可以在此处找到一种实用的方法。 The idea is to parse the path by splitting over the | 这个想法是通过分割|来解析路径| character, and then build the object on the fly. 角色,然后动态生成对象。

const arr = [
  {cat : 'one|two|thre|boo'},
  {cat : 'one|two|boo|boo|ouch'},
  {cat : 'one|two|thre|boo|lee'},
  {cat : 'one|hey|something|other'},
  {cat : 'one|hey|keys|other'},
  {cat : 'this|blaj|something|other'},
];


function create(array) {
  const parse = elm => elm.cat.split('|');

  const build = (keys, obj, acc) => {
    keys.reduce((a, b) => {
        if (!a[b]) a[b] = {};
        return a[b];
      }, obj);
    Object.assign(acc, obj);
    return acc;
  };

  const obj = {};

  return array
    .map(a => parse(a))
    .reduce((acc, keys) => build(keys, obj, {}), {});
}

console.log(create(arr))

You can find the Working plunkr 您可以找到工作中的朋克

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM