【问题标题】:map array with dots between names to nested fields将名称之间带点的数组映射到嵌套字段
【发布时间】:2021-04-30 09:59:26
【问题描述】:

我正在尝试转换名称之间带有点的字符串数组。我想制作一个像const out 这样的对象数组。我尝试通过reduceRight来实现,但是我不知道如何组合字段。

我的代码:

const input = ['apples', 'bananas.kivi.grape', 'bananas.orange', 'bananas.strawberry'];
const res = input.map((item) => {
  const splInp = item.split('.');
  return splInp.reduceRight((acc, item) => {
    if (Object.keys(acc).length !== 0) {
      return {
        children: [acc],
        "name": item
      };
    } else {
      return {
        "name": item
      };
    }
  }, []/* as any*/);
});
console.log(res);

期望的输出:

const out = [
  { name: 'apples' },
  {
    name: 'bananas',
    children: [
      {
        name: 'kivi',
        children: [
          {
            name: 'grape',
          },
        ],
      },
      { name: 'orange' },
      { name: 'strawberry' },
    ],
  },
];

【问题讨论】:

    标签: javascript arrays string performance


    【解决方案1】:

    您可以使用trie 解决它

    只要你得到一个字符串,就遍历你的树并最终添加任何叶子(如果你不能遍历更多)

    const input = ['apples', 'bananas.kivi.grape', 'bananas.orange', 'bananas.strawberry', 'apples.are.good', 'apples.are.not.good'];
    const Trie = () => {
      const root = {}
      const add = s => {
        s.split('.').reduce((acc, tok) => {
          if (!acc[tok]) {
            // add the leaf
            acc[tok] = { children: {} }
          }
          // traverse the node
          return acc[tok].children
        }, root)
      }
      const toJSON = (node = root) => {
        return Object.entries(node).map(([name, { children }]) => ({
          name, children: toJSON(children)
        }))
      }
      return { add, toJSON }
    }
    const t = Trie()
    input.forEach(t.add)
    console.log(JSON.stringify(t.toJSON(), null, 2))

    【讨论】:

    • 在最后一个元素中我们应该跳过子数组,所以应该是{ name: 'strawberry' }, no { "name": "strawberry", "children": [] }
    • 我让您尝试修改 toJSON 以避免在 toJSON(children) 返回空时返回子级。如果你仍然不能,我会更新@quippe
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-29
    • 2020-09-01
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    • 2017-05-27
    • 1970-01-01
    相关资源
    最近更新 更多