1

I am receiving the following structure from a system. I am attempting to bend it into the form needed for a particular graph utilizing chartjs. Given the JSON data structure … an array of objects in an object:

{
"chart": [
    {
        "date": "2018-10-29",
        "done": 3,
        "todo": 10

    },
    {
        "date": "2018-10-30",
        "done": 4,
        "todo": 7
    },
    {
        "date": "2018-10-31",
        "done": 5,
        "todo": 12
    }
]

}

I need the desired JSON data structure ... an object of arrays (in one array, in one object)

{
"chart": [{
    "date": [
        "2018-10-29",
        "2018-10-29",
        "2018-10-31"
    ],
    "done": [
        3,
        4,
        5
    ],
    "todo": [
        10,
        7,
        12
    ]
}]

}

I have attempted to use the .map function but I don't seem to have the correct map-fu.

Jim
  • 359
  • 2
  • 15
  • Possible duplicate of [Multi-dimensional associative arrays in JavaScript](https://stackoverflow.com/questions/4329092/multi-dimensional-associative-arrays-in-javascript) – Himanshu Nov 01 '18 at 19:55

3 Answers3

2

You could take an object and get all keys with ther values in single array.

var data = { chart: [{ date: "2018-10-29", done: 3, todo: 10 }, { date: "2018-10-30", done: 4, todo: 7 }, { date: "2018-10-31", done: 5, todo: 12 }] },
    result = { chart: data.chart.reduce((r, o) => {
            Object.entries(o).forEach(([k, v]) => (r[k] = r[k] || []).push(v));
            return r;
        }, {})
    };
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • This worked perfectly and was exactly what I had hoped for. Thank you for the quick response. – Jim Nov 01 '18 at 20:11
1

What about using reduce ?

const output = input.reduce((acc, curr) => ({
  date: acc.date.concat(curr.date),
  done: acc.done.concat(curr.done),
  todo: acc.todo.concat(curr.todo),
}), { date: [], done: [], todo: [] });

const chartData = {
  chart: [output],
};

Reference for reduce is here : https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/reduce

SylvainAr
  • 154
  • 5
0

Here's a very explicit solution. There may be some slicker Javascript solutions; certainly you can do multiple .map calls, but that makes it less efficient.

// Variables
var dates = [];
var doneValues = [];
var todoValues = [];

// Loop through the original data once, collect the data.
originalJSON.forEach(function(data) {
  dates.push(data["date"]);
  doneValues .push(data["done"]);
  todoValues .push(data["todo"]);
});

// Put it all together.
return {"chart": [{"date": dates, "done": doneValues , "todo": todoValues}]};

Modify it to suit your needs.

MrDanA
  • 11,489
  • 2
  • 36
  • 47