[英]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.
我试图将它弯曲成利用chartjs的特定图形所需的形式。 Given the JSON data structure … an array of objects in an object:
给定JSON数据结构......对象中的对象数组:
{
"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) 我需要所需的JSON数据结构......数组的对象(在一个数组中,在一个对象中)
{
"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. 我试图使用.map函数,但我似乎没有正确的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 ? 使用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 reduce的参考资料如下: 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;
可能有一些更流畅的Javascript解决方案; certainly you can do multiple
.map
calls, but that makes it less efficient. 当然你可以做多个
.map
调用,但这会降低效率。
// 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. 修改它以满足您的需求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.