javascript - Lodash - 如何从平面数组创建树

标签 javascript json lodash

每次加载我的应用程序时,我都会收到以下 json:

[
  {
    id: 'mALRRY93jASr',
    identifier: '100',
    text: 'Text A'
  },
  {
    id: '7S3xHZEdNcfV',
    identifier: '200',
    text: 'Text B'
  },
  {
    id: '2ZA5xSJeukU6',
    identifier: '300',
    text: 'Text C',
  },
  {
    id: 'bhg3GnLEvw2k',
    identifier: '300.100',
    text: 'Text C - A'
  },
  {
    id: 'bhg3GnLEvw2k',
    identifier: '300.100.100',
    text: 'Text C - A - A'
  },
  {
    id: '2AcXNr4HT388',
    identifier: '300.200',
    text: 'Text C - B'
  }
]

树级别由 identifier 属性标识。

树可以有数千个子节点,因此它需要递归。

如何使用 Lodash 排列 json看起来像下面的 json

[
  {
    id: 'mALRRY93jASr',
    identifier: '100',
    text: 'Text A'
  },
  {
    id: '7S3xHZEdNcfV',
    identifier: '200',
    text: 'Text B'
  },
  {
    id: '2ZA5xSJeukU6',
    identifier: '300',
    text: 'Text C',
    children: [
      {
        id: 'bhg3GnLEvw2k',
        identifier: '300.100',
        text: 'Text C - A',
        children: [
          {
            id: 'bhg3GnLEvw2k',
            identifier: '300.100.100',
            text: 'Text C - A - A'
          }
        ]
      },
      {
        id: '2AcXNr4HT388',
        identifier: '300.200',
        text: 'Text C - B'
      }
    ]
  }
]

最佳答案

您可以采用迭代方法,在标识符的同一路径中查找对象并构建嵌套结构。

此方法也适用于未排序的数据。

var data = [{ id: 'mALRRY93jASr', identifier: '100', text: 'Text A' }, { id: '7S3xHZEdNcfV', identifier: '200', text: 'Text B' }, { id: '2ZA5xSJeukU6', identifier: '300', text: 'Text C' }, { id: 'bhg3GnLEvw2k', identifier: '300.100', text: 'Text C - A' }, { id: 'bhg3GnLEvw2k', identifier: '300.100.100', text: 'Text C - A - A' }, { id: '2AcXNr4HT388', identifier: '300.200', text: 'Text C - B' }],
    tree = [];

data.reduce((r, o) => {
    o.identifier
        .split('.')
        .map((_, i, a) => a.slice(0, i + 1).join('.'))
        .reduce((q, identifier, i, { length }) => {
            var temp = (q.children = q.children || []).find(p => p.identifier === identifier);
            if (!temp) {
                q.children.push(temp = { identifier });
            }
            if (i + 1 === length) {
                Object.assign(temp, o);
            }
            return temp;
        }, r);
    return r;
}, { children: tree });

console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - Lodash - 如何从平面数组创建树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53818897/

相关文章:

javascript - 时间格式的正则表达式验证

jquery - 我需要在此 jQuery 自动完成示例中更改哪些内容才能使其与我的 JSON url 一起使用?

c# - .NET 中的 JSON 反序列化

json - 由于数据类型不匹配而获取 : argument 2 requires integral type error while parsing Json data Spark SQL

javascript - 如何在$q下传递多个$http promise

javascript - 如何展平对象的嵌套嵌套数组

javascript - 将数组中的所有其他值移动到新数组中

javascript - 如何将 GMT 时间戳转换为 Unix 时间戳 (javascript)

javascript - 在 VueJS 中访问 $route.params

javascript - 在 .HTA 程序中,如何更改脚本中的运行图标(VBScript 或 Javascript 都可以)?