[英]Transform a list of dictionaries into a dictionary of lists with Javascript
是否有内置的 Javascript function 来转换字典列表:
const L =
[ { "day": "20201210", "count": "100" }
, { "day": "20201211", "count": "120" }
, { "day": "20201212", "count": "90" }
, { "day": "20201213", "count": "150" }
]
放入这样的列表字典中:
const D =
{ "day" : [ "20201210", "20201211", "20201212", "20201213"]
, "count" : [ "100", "120", "90", "150"]
}
? 如果不是,在 JS 中最简单的方法是什么?
(它有点类似于矩阵“转置”操作)。
注意:这里是一个转置而不是像在对象数组上分组的最有效方法中那样的分组
假设所有对象都具有相同的键并且您的数组不为空,这将起作用:
let D = {};
Object.keys(L[0]).forEach(k => {
D[k] = L.map(o => o[k]);
});
当然有更有效的解决方案,但这是简短明了的,而且在效率方面也不算太差。
这是一个相当简短且有效的通用值方法。
L.forEach(o => {
Object.keys(o).forEach(k => {
D[k] ||= [];
D[k].push(o[k]);
});
});
const L = [{ "day": "20201210", "count": "100" }, { "day": "20201211", "count": "120" }, { "day": "20201212", "count": "90" }, { "day": "20201213", "count": "150" }] let D = {}; L.forEach(o => { Object.keys(o).forEach(k => { D[k] ||= []; D[k].push(o[k]); }); }); console.log(D);
我认为这样的 function 不存在,至少在 vanilla JavaScript 中是这样。
一个简单、纯粹的香草和清晰易懂的方式是这样的:
var L = [
{
"day": "20201210",
"count": "100"
},
{
"day": "20201211",
"count": "120"
},
{
"day": "20201212",
"count": "90"
},
{
"day": "20201213",
"count": "150"
}
];
var D = { };
for (var dict in L)
{
for (var key in L[dict])
{
if (D[key] == null) {
D[key] = [ ];
}
D[key].push(L[dict][key]);
}
}
这绝对不是最简洁或最优化的方法,尽管它会起作用。
你可以这样重组你的字典数组,然后用Array.prototype.map重新映射它
例如(下面的练习需要用map
N * X
次迭代元素,其中N
是L
的长度, X
是你想要在D
中拥有的属性数量,如果你有很多你想要的属性,请忽略这个观看。)
但是,这是我想在第二种方法之前向您介绍的最简单可读的方法。
const L = [{"day":"20201210","count":"100"},{"day":"20201211","count":"120"},{"day":"20201212","count":"90"},{"day":"20201213","count":"150"}]; const D = { 'day': L.map(elem => elem['day']), 'count': L.map(elem => elem['count']), }; console.log(D);
我建议的另一种方法是使用Array.prototype.reduce ,这在您的情况下是迄今为止最受青睐的,因为它可以通过向初始数组添加更多属性来轻松扩展。
const L = [{"day":"20201210","count":"100"},{"day":"20201211","count":"120"},{"day":"20201212","count":"90"},{"day":"20201213","count":"150"}]; const D = L.reduce((acc, cv) => { for (const propertyToGrab in acc) { if (cv.hasOwnProperty(propertyToGrab)) { acc[propertyToGrab].push(cv[propertyToGrab]); } } return acc; }, { 'day': [], 'count': [] }); console.log(D);
const D={day:[], count:[]};
for(const item of L){
D.day.push(item.day);
D.count.push(item.count);
}
const input = [{"day":"20201210","count":"100"},{"day":"20201211","count":"120"},{"day":"20201212","count":"90"},{"day":"20201213","count":"150"}];
// Create a variable that will store the result
let result = {};
// Loop through the input with forEach
input.forEach((element) => {
// Loop through the keys
for(let key in element) {
// Check if a key is not exist in the result
if(!result.hasOwnProperty(key)) {
// Then create an key and assign an empty array to it
result[key] = [];
}
// Push the elemnts to the array.
result[key].push(element[key]);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.