Lucas Verra Lucas Verra - 18 days ago 6
Javascript Question

js array of dict into multiple arrays

Is there an intelligent (so no for loop) way of changing this

[ { date: Mon Aug 08 2016 16:59:16 GMT+0200 (CEST),
visits: 0,
hits: 578,
views: 5131 },
{ date: Tue Aug 09 2016 16:59:16 GMT+0200 (CEST),
visits: -1,
hits: 548,
views: 722 },
{ date: Wed Aug 10 2016 16:59:16 GMT+0200 (CEST),
visits: -1,
hits: 571,
views: 4772 }]


into this

var dates = [date1,date2,...]
var visits = [visits,visits,...]
var hits = [hits,hits,...]
var views = [vews1,vews2,...]


The idea is be able to plot that using plot.ly multiple axis

Answer

You can to use map:

var array =  [ { "date": 'Mon Aug 08 2016 16:59:16 GMT+0200 (CEST)',
    visits: 0,
    hits: 578,
    views: 5131 },
  { "date": 'Tue Aug 09 2016 16:59:16 GMT+0200 (CEST)',
    visits: -1,
    hits: 548,
    views: 722 },
  { "date": 'Wed Aug 10 2016 16:59:16 GMT+0200 (CEST)',
    visits: -1,
    hits: 571,
    views: 4772 }];

var dates = array.map(item => item.date);
var visits = array.map(item => item.visits);
var hits = array.map(item => item.hits);
var views = array.map(item => item.views);

console.log(dates, visits, hits, views);

Comments