【问题标题】:Flatten an array with children using Lodash and TypeScript使用 Lodash 和 TypeScript 将包含子元素的数组展平
【发布时间】:2021-05-07 08:22:56
【问题描述】:

使用 TypeScript 代码,我试图展平一个对象数组,其中每个元素都可以包含子元素:

function getMenu (menus:Array<Menu>, name:string | undefined) {
  console.log('getMenu', name, menus[0])
  const test = _(menus)
    .thru(function (coll) {
      return _.union(coll, _.map(coll, 'children') || [])
    })
  console.log('getMenu 2', test)
  return name
}

我遇到了阻止我的错误:

“Menu[][]”类型的参数不能分配给“List”类型的参数。

索引签名不兼容。

“Menu[]”类型缺少“Menu”类型的以下属性:标签、图标、路线、可选择和另外 2 个。

注意:该代码在 JavaScript 中运行良好。

【问题讨论】:

标签: typescript lodash


【解决方案1】:

_.map(coll, 'children') 返回菜单[][]。我们应该将其展平以使其成为 Menu[]。

试试下面的代码:

function getMenu(menus: Array<Menu>, name: string | undefined) {
  console.log('getMenu', name, menus[0]);
  const test = _(menus).thru(function(coll) {
     const flattenData = flatten(_.map(coll, 'children')); // flattening the data here
    return _.union(coll, flattenData);
  });
  return name;
}

【讨论】:

  • 我有这个错误:“菜单[][]”类型上不存在属性“平面”。您需要更改目标库吗?尝试将 lib 编译器选项更改为“es2019”或更高版本。
  • 我在您提供的 stackblitz 链接中进行了尝试。你能更新并给我吗?
  • 我做了这个,没关系:``` function getMenu (menus:Array, name:string | undefined) :Menu|undefined { return (menus).thru(function (coll) { const flattenData:Array = _.flatten(.map(coll, 'children')) return _.union(coll, flattenData) }) .flatten() .find({ route : 名称 }) } ```
  • @franfrLor 立即尝试更新的代码。我使用了 lodash flatten 运算符来展平它。不要忘记从 lodash 导入扁平化。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-17
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多