有什么方法可以用更有效的替换链'.map'...'。map'...'。pluck'...'。map'吗?

时间:2018-10-29 08:06:19

标签: javascript arrays

我有一个数组:

[
    { "time": "Mon May 14 2018", "points": { "a": 1, "b": 2, "c": 3} },
    { "time": "Mon May 14 2017", "points": { "a": 5, "b": 6, "c": 7} }
]

我需要将其转换为以下格式:

[
 {
  eventTime:"Mon May 14 2018",
  series: [
    {
      name: "a",
      value: 1
    },
    {
      name: "b",
      value: 2
    },
    {
      name: "c",
      value: 3
    }
  ]
 },
 {
  eventTime:"Mon May 14 2017",
  series: [
    {
      name: "a",
      value: 5
    },
    {
      name: "b",
      value: 6
    },
    {
      name: "c",
      value: 7
    }
  ]
 }
]

我有一段代码可以进行转换:

.map(x =>
  x.map(y => _.pick(y, ['time', 'event'])).map(z => ({
    name: z.eventTime,
    series: [
      {
        name: 'a',
        value: z.event.a
      },
      {
        name: 'b',
        value: z.event.b
      },
      {
        name: 'c',
        value: z.event.c
      }
    ]
  }))
)

您认为这样做有更好的方法吗? 我看到有一个函数_.transform,但没有弄清楚它对我的情况有什么帮助。

不寻找带有纯for..each循环的解决方案

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

[
    { time: "Mon May 14 2018", points: { "a": 1, "b": 2, "c": 3} },
    { time: "Mon May 14 2017", points: { "a": 5, "b": 6, "c": 7} }
].map(obj => ({
    eventTime: obj.time,
    series: [
        { name: "a", value: obj.points.a },
        { name: "b", value: obj.points.b },
        { name: "c", value: obj.points.c }
    ]
}))

[
    { time: "Mon May 14 2018", points: { "a": 1, "b": 2, "c": 3} },
    { time: "Mon May 14 2017", points: { "a": 5, "b": 6, "c": 7} }
].map(obj => ({
    eventTime: obj.time,
    series: Object.keys(obj.points).map(key => ({ name: key, value: obj.points[key] }))
}))

答案 1 :(得分:1)

您可以仅使用map方法和ES6参数解构来完成此操作。

let data = [{ "time": "Mon May 14 2018", "points": { "a": 1, "b": 2, "c": 3}}, { "time": "Mon May 14 2017", "points": { "a": 5, "b": 6, "c": 7}}]

let result = data.map(({time, points}) => ({
  eventTime: time,
  series: Object.entries(points).map(([name, value]) => ({name, value}))
}))

console.log(result)