简体   繁体   中英

How to Convert an Array of Objects into an Object of Associative Arrays in Javascript

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.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM