3

I have like to use chartkick and so I have like to convert the following object:

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}]

To the following format:

var arrayOne = [{'01/01/2017': 200 , '02/01/2017': 220 , '03/01/2017':250}]

Any help would be greatly appreciated.

MauriceNino
  • 6,214
  • 1
  • 23
  • 60
Daryl Wong
  • 2,023
  • 5
  • 28
  • 61

2 Answers2

1

You could just reduce it like in the following example. Don't know why you need to have an array with a single element as an output, but if you really need that, just wrap it with []

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);
MauriceNino
  • 6,214
  • 1
  • 23
  • 60
1

using map also you could do that

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);
MauriceNino
  • 6,214
  • 1
  • 23
  • 60