使用 ES6 将数据从一种形式转换为另一种形式
Transform the data from one form to another using ES6
我有如下数据:
[
{
name: "ABC",
points: [
{
timestamp: "2017/09/26",
value: 1
},
{
timestamp: "2017/09/27",
value: 2
},
]
},
{
name: "DEF",
points: [
{
timestamp: "2017/09/26",
value: 0
},
{
timestamp: "2017/09/27",
value: 3
},
]
}
]
我想将以上数据转化为:
[
{
timestamp: "2017/09/26",
"ABC": 1,
"DEF": 0
},
{
timestamp: "2017/09/27",
"ABC": 2,
"DEF": 3
}
]
我刚开始学习 ES6 和下划线。尝试使用下划线进行转换,但无法成功。
您可以通过以下方式进行
let arr = [
{
name: "ABC",
points: [
{
timestamp: "2017/09/26",
value: 1
},
{
timestamp: "2017/09/27",
value: 2
},
]
},
{
name: "DEF",
points: [
{
timestamp: "2017/09/26",
value: 0
},
{
timestamp: "2017/09/27",
value: 3
},
]
}
]
let result = arr.reduce((a, b) => {
for(let element of b.points){
a[element.timestamp] = a[element.timestamp] || {};
let newObj = {};
newObj[b.name] = element.value;
Object.assign(a[element.timestamp], newObj);
}
return a;
}, {});
result = Object.keys(result).map(key => Object.assign(result[key], {timestamp : key}));
console.log(result);
由于你没有共同努力,我将把这个答案集中在算法上,并将实现部分留给你。
算法:
- 创建一个将存储组的哈希图。
- 一个群会有一个签名
{ name: valueAsPerDate}
- 现在循环数据。对于每一个对象,
- 在哈希图中搜索当前日期。如果存在,请添加具有必要值的组。
- 如果没有,将其添加到 hashmap,然后向其添加组值。
- 一旦上述循环结束,再次循环 hashmap 和你格式的 return 对象,其中 timestamp 将是你的组名,你已经在该对象中有值。
哒哒!!!
我有如下数据:
[
{
name: "ABC",
points: [
{
timestamp: "2017/09/26",
value: 1
},
{
timestamp: "2017/09/27",
value: 2
},
]
},
{
name: "DEF",
points: [
{
timestamp: "2017/09/26",
value: 0
},
{
timestamp: "2017/09/27",
value: 3
},
]
}
]
我想将以上数据转化为:
[
{
timestamp: "2017/09/26",
"ABC": 1,
"DEF": 0
},
{
timestamp: "2017/09/27",
"ABC": 2,
"DEF": 3
}
]
我刚开始学习 ES6 和下划线。尝试使用下划线进行转换,但无法成功。
您可以通过以下方式进行
let arr = [
{
name: "ABC",
points: [
{
timestamp: "2017/09/26",
value: 1
},
{
timestamp: "2017/09/27",
value: 2
},
]
},
{
name: "DEF",
points: [
{
timestamp: "2017/09/26",
value: 0
},
{
timestamp: "2017/09/27",
value: 3
},
]
}
]
let result = arr.reduce((a, b) => {
for(let element of b.points){
a[element.timestamp] = a[element.timestamp] || {};
let newObj = {};
newObj[b.name] = element.value;
Object.assign(a[element.timestamp], newObj);
}
return a;
}, {});
result = Object.keys(result).map(key => Object.assign(result[key], {timestamp : key}));
console.log(result);
由于你没有共同努力,我将把这个答案集中在算法上,并将实现部分留给你。
算法:
- 创建一个将存储组的哈希图。
- 一个群会有一个签名
{ name: valueAsPerDate}
- 现在循环数据。对于每一个对象,
- 在哈希图中搜索当前日期。如果存在,请添加具有必要值的组。
- 如果没有,将其添加到 hashmap,然后向其添加组值。
- 一旦上述循环结束,再次循环 hashmap 和你格式的 return 对象,其中 timestamp 将是你的组名,你已经在该对象中有值。
哒哒!!!