Javascript 转换对象以制作图表
Javascript convert object for charting
我喜欢使用 chartkick 所以我想转换以下对象:
var array = [{date:'01/01/2017',value1:200,value2:300,value3:400}, {date:'02/01/2017',value1:220,value2:330,value3:430},{date:'03/01/2017',value1:250,value2:330,value3:420}]
格式如下:
var arrayOne = [{'01/01/2017': 200 , '02/01/2017': 220 , '03/01/2017':250}]
如有任何帮助,我们将不胜感激。
您可以像下面的示例一样减少它。不知道为什么你需要一个包含单个元素的数组作为输出,但如果你真的需要它,只需用 []
包装它
const array = [{date:'01/01/2017',value1:200,value2:300,value3:400}, {date:'02/01/2017',value1:220,value2:330,value3:430},{date:'03/01/2017',value1:250,value2:330,value3:420}]
const obj = array.reduce((acc, o) => {
acc[o.date] = o.value1;
return acc;
}, {});
console.log(obj);
你也可以使用地图
var arra = [{ date: '01/01/2017', value1: 200, value2: 300, value3: 400 }, { date: '02/01/2017', value1: 220, value2: 330, value3: 430 }, { date: '03/01/2017', value1: 250, value2: 330, value3: 420 }]
var finalArr = arra.map(data => {
let obje = {}
obje[data.date] = data.value1
return obje
})
console.log(finalArr);
我喜欢使用 chartkick 所以我想转换以下对象:
var array = [{date:'01/01/2017',value1:200,value2:300,value3:400}, {date:'02/01/2017',value1:220,value2:330,value3:430},{date:'03/01/2017',value1:250,value2:330,value3:420}]
格式如下:
var arrayOne = [{'01/01/2017': 200 , '02/01/2017': 220 , '03/01/2017':250}]
如有任何帮助,我们将不胜感激。
您可以像下面的示例一样减少它。不知道为什么你需要一个包含单个元素的数组作为输出,但如果你真的需要它,只需用 []
const array = [{date:'01/01/2017',value1:200,value2:300,value3:400}, {date:'02/01/2017',value1:220,value2:330,value3:430},{date:'03/01/2017',value1:250,value2:330,value3:420}]
const obj = array.reduce((acc, o) => {
acc[o.date] = o.value1;
return acc;
}, {});
console.log(obj);
你也可以使用地图
var arra = [{ date: '01/01/2017', value1: 200, value2: 300, value3: 400 }, { date: '02/01/2017', value1: 220, value2: 330, value3: 430 }, { date: '03/01/2017', value1: 250, value2: 330, value3: 420 }]
var finalArr = arra.map(data => {
let obje = {}
obje[data.date] = data.value1
return obje
})
console.log(finalArr);