使用地图标准化数据失败

时间:2017-08-23 11:25:57

标签: javascript ecmascript-6

我想使用地图重建数据,我该怎样转向

[{
    date: "2017-08-19",
    female_count: 4,
    male_count: 5,
    total_count: 9
},
{
    date: "2017-08-20",
    female_count: 120,
    male_count: 14,
    total_count: 134
}]

进入这个

[{
    date: "2017-08-19",
    total: 9,
    data: [{
        name: "male",
        value: 4,
        color: "blue" 
    },{
        name: "female",
        value: 5,
        color: "red" 
    }]
}]

我的失败尝试,我坚持将男性和女性数量推入新的数据属性。

data.map(obj => {

        let temp = {
            date: data.date,
            total: data.total_count
        }

        temp['data'] = {
            name: "male",
            value: obj.male_count,
            color: "blue"
        }

        temp['data'] = {
            name: "female",
            value: obj.female_count,
            color: "red"
        }

        return temp
    })
女性会覆盖男性,不确定我应该使用推动。需要帮助。

3 个答案:

答案 0 :(得分:1)

问题是您使用data作为对象,而不是数组,并为每个元素重写它。将其声明为数组:data: [],并使用push方法添加元素。



let items = [
  {
    date: "2017-08-19",
    female_count: 4,
    male_count: 5,
    total_count: 9
  },
  {
    date: "2017-08-20",
    female_count: 120,
    male_count: 14,
    total_count: 134
  }
];

let newItems = items.map(obj => {
  let item = {
    date: obj.date,
    total: obj.total_count,
    data: []
  };
  item.data.push({
    name: "male",
    value: obj.male_count,
    color: "blue"
  });
  item.data.push({
    name: "female",
    value: obj.female_count,
    color: "red"
  });
  return item;
});

console.log(newItems);




答案 1 :(得分:0)

我不确定你是如何达到颜色属性的,但如果你考虑基于性别的颜色,这可能是一个解决方案



const input = [{
    date: "2017-08-19",
    female_count: 4,
    male_count: 5,
    total_count: 9
},
{
    date: "2017-08-20",
    female_count: 120,
    male_count: 14,
    total_count: 134
}]

const output = input.map((v) => {
  const data = [
    {
      name: "male",
      value: v.male_count,
      color: "blue" 
    },
    {
      name: "female",
      value: v.female_count,
      color: "red" 
    }
  ];
  
  return {
    date: v.date,
    total: v.total_count,
    data: data
  };  
});

console.log('>>>>output', output);




答案 2 :(得分:0)

基于@ alexmac的解决方案,您可以将meteor回调写为单个对象:

map

(花括号周围的括号是创建对象而不是函数体所必需的。)