【问题标题】:Map array of objects into new groups将对象数组映射到新组中
【发布时间】:2021-03-31 12:26:39
【问题描述】:

我有一个对象,其中包含从 API 返回的两个对象数组。我需要尝试将其映射到一个新的对象数组中,以便可以对 Vue v-select 组件的数据进行分组。 CodePen Example

fields: {
      current: [
        {
          name: 'Date'
        },
        {
          name: 'Time'
        }
      ],
      previous: [
        {
          name: 'Birthday'
        },
        {
          name: 'Comments'
        }
      ]
    },

我怎样才能将它映射到一个看起来像这样的新对象数组中?

grouped: [
      {
        group: "Current",
      },
      {
        name: "Date"
      },
      {
        name: "Time"
      },
      {
        group: "Previous"
      },
      {
        name: "Birthday"
      },
      {
        name: "Comments"
      },
    ]

【问题讨论】:

    标签: javascript arrays dictionary javascript-objects v-select


    【解决方案1】:

    使用Object.entries() 获取组及其值,并使用Array.flatMap() 映射它们。创建组的对象,并将其添加到包含组项的数组中。

    const flattenGroups = fields =>
      Object.entries(fields)
        .flatMap(([group, items]) => [{ group }, ...items])
    
    const fields = {"current":[{"name":"Date"},{"name":"Time"}],"previous":[{"name":"Birthday"},{"name":"Comments"}]}
    
    const result = flattenGroups(fields)
    
    console.log(result)

    【讨论】:

    • 太棒了!谢谢!我试图用reduce 来做这件事,但有点搞混了。这很好,简洁。
    • 不客气。愿你找到丢失的树皮:)
    猜你喜欢
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    • 2021-04-18
    • 1970-01-01
    • 2022-11-24
    • 2020-03-19
    • 2020-07-22
    • 1970-01-01
    相关资源
    最近更新 更多