【问题标题】:creating a dictionary from a javascript array [closed]从javascript数组创建字典[关闭]
【发布时间】:2017-11-01 14:06:48
【问题描述】:

我得到了以下形式的对象数组:

let postArray = [
   {
      id = 1,
      body = "some text"
   },
   {
      id = 2,
      body = "some other text"
   }
]

我想将其重新排列为以下形式:

{
    posts: {
      1: {
          id = 1,
          body = "some text"
       },
      2: {
          id = 2,
          body = "some other text"
       }
    }
}

如何使用 ES6 做到这一点?

【问题讨论】:

标签: javascript ecmascript-6


【解决方案1】:

你可以减少你的数组:

let postArray = [
   {
      id: 1,
      body: "some text"
   },
   {
      id: 2,
      body: "some other text"
   }
]
const posts = postArray.reduce((acc, b) => ({...acc, [b.id]: b}), {})
const result = { posts }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-28
    • 2020-01-18
    • 2013-05-12
    相关资源
    最近更新 更多