【问题标题】:Transform an array to another array将一个数组转换为另一个数组
【发布时间】:2017-10-23 13:42:46
【问题描述】:

我想使用 lodash 2.4.2 将此数组转换为另一个数组:

权限将映射到角色中。并且我们不会触及其他属性。

发件人:

      {

      "items": [
        {
          "_id": "admin",
          "authorities": [
            {
              "name": "ROLE_ADMIN"
            }
          ]
        },
        {
          "_id": "user",
          "authorities": [
            {
              "name": "ROLE_USER"
            }
          ]
        }
      ]
    }

到这个数组

    {

    "items": [
        {
          "_id": "admin",
          "roles": [

              "ROLE_ADMIN"

          ]
        },
        {
          "_id": "user",
          "role": [

              "ROLE_USER"

          ]
        }
      ]
    }

你能帮帮我吗?

【问题讨论】:

  • Stackoverflow 不是免费的代码编写服务。展示你尝试过的东西。这里的目标是帮助您修复您的代码

标签: javascript lodash


【解决方案1】:

正如charlietfl 所说,在以后的帖子中,您必须提供您为解决问题而编写的代码示例。

这是解决方案,非常简单:

const initialObject = {
  "items": [
    {
      "_id": "admin",
      "authorities": [
        {
          "name": "ROLE_ADMIN"
        }
      ]
    }, 
    {
      "_id": "user",
      "authorities": [
        {
          "name": "ROLE_USER"
        }
      ]
    }
  ]
}

const processedObject = _
  .map(initialObject.items, item => {
    return {
      _id: item._id,
      roles: _.map(item.authorities, a => a.name)
    }
  })

【讨论】:

    【解决方案2】:

    这只是键名的重新映射。出于性能原因,我会尽量避免使用delete。您可以在此 benchmark 中看到性能差异,仅当对象稍后被持久化时才使用“删除”。

    for (var item of items) {
      item.roles =  item.authorities
      // possible but slow
      // delete item.authorities
      item.authorities = undefined
    }
    

    编辑:如果您想避免对象本身的突变和清理属性,@vanelizarov 代码会更好。但它也比较慢。

    vanelizarov code:   x 5,025,370 ops/sec ±1.30% (90 runs sampled)
    my code:            x 31,583,811 ops/sec ±0.95% (92 runs sampled)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-17
      • 2020-06-05
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多