转换数据

时间:2017-09-25 11:08:11

标签: javascript underscore.js

我有以下数据结构:

const data = [
  {
    name: 'ABC',
    salesData: [
      {
        timestamp: '2017-09-01',
        value: 10
      },
      {
        timestamp: '2017-09-02',
        value: 2
      }
    ]
  },
  {
    name: 'DEF',
    salesData: [
      {
        timestamp: '2017-09-01',
        value: 8
      },
      {
        timestamp: '2017-09-02',
        value: 3
      }
    ]
  }
];

我想将其转换为:

[
  {
    name: 'ABC',
    '2017-09-01': 10,
    '2017-09-02': 2
  },
  {
    name: 'CDE',
    '2017-09-01': 8,
    '2017-09-02': 3
  }
]

我正在尝试使用Underscore的链和地图,这让我很困惑。到目前为止,我有以下内容,不知道如何根据需要编写convertedSalesData进行转换:

_.map(data, function(item) {
    let name = item.name;
    let salesData = item.salesData;
    let convertedSalesData = ?
})

3 个答案:

答案 0 :(得分:2)

使用ES6,您可以使用扩展语法...来获得此结果。



const data = [{"name":"ABC","salesData":[{"timestamp":"2017-09-01","value":10},{"timestamp":"2017-09-02","value":2}]},{"name":"DEF","salesData":[{"timestamp":"2017-09-01","value":8},{"timestamp":"2017-09-02","value":3}]}]


var result = data.map(function({name, salesData}) {
  return {name, ...Object.assign({}, ...salesData.map(({timestamp, value}) => ({[timestamp]: value})))}
})
console.log(result)




答案 1 :(得分:2)



const data = [{
    name: 'ABC',
    salesData: [{
        timestamp: '2017-09-01',
        value: 10
      },
      {
        timestamp: '2017-09-02',
        value: 2
      }
    ]
  },
  {
    name: 'DEF',
    salesData: [{
        timestamp: '2017-09-01',
        value: 8
      },
      {
        timestamp: '2017-09-02',
        value: 3
      }
    ]
  }
];

var res = data.map(function(a) {
  var obj = {
    name: a.name
  };
  a.salesData.forEach(function(x) {
    obj[x.timestamp] = x.value;
  })
  return obj;
})

console.log(res);




答案 2 :(得分:2)

与@Nenad Vracar相似。我更愿意使用' reduce':

data.map(({ name, salesData }) => ({
  name,
  ...salesData.reduce(
    (record, { timestamp, value }) => {
      record[timestamp] = value
      return record
    },
    Object.create(null)
  )
}))