如何迭代对象数组并按其键名对属性值进行分组? [英] How to iterate an array of objects and group the property values by their key name?
问题描述
我有一个名为 data 的对象数组,如下所示:
I have an array of objects named data, like so:
data = [{"timeslot":"7pm-8pm","Monday":60,"Tuesday":55},
{"timeslot":"8pm-9pm","Monday":70,"Tuesday":60},
{"timeslot":"9pm-10pm","Monday":40,"Tuesday":37}]
我想从该数组中获得三个新数组,如下所示:
I want to get from this array three new arrays, like so:
timeslot = ["7pm-8pm", "8pm-9pm", "9pm-10pm"]
monday = [60, 70, 40]
tuesdat = [55, 60, 37]
通过数据值所属的 data 属性名称有效地对它们进行分组.
Effectively grouping the data values by the data property name to which they belong.
这是我的 JavaScript
var timeslot = [];
var monday = [];
var tuesday = [];
var result = {};
// Iterate the objects of the array
for(var i = 0, len = data.length; i < len; i++) {
var obj = data[i];
// Iterate the properties of the object
Object.keys(obj).forEach(function(key) {
// Push the value of each property to an array sharing the property's key name
result[key.toLowerCase()] = [obj[key]];
});
}
console.log(result.timeslot, result.monday, result.tuesday);
这将返回
["9pm-10pm"] [40] [37]
这些是 data 的第三个也是最后一个对象的属性值. 似乎forEach中的代码将新数组的前一个元素替换为当前元素.每个新数组仅包含一个元素,而不是所需的三个.
These are the property values of data's third and final object. It appears that the code inside the forEach is replacing the previous element of the new array with the current element. The new arrays each contain only one element, instead of the desired three.
我该如何解决?
推荐答案
您的代码存在的问题是,当您遍历keys
数组时,每次都在这里替换先前的值
The issue with your code is that, while you are iterating over the keys
array, you are replacing the previous value each time here
result[key.toLowerCase()] = [obj[key]]; // This is replacing the existing value
To add a new entry to an array, you can use Array.push() method as shown below :
result[key.toLowerCase()].push([obj[key]]);
var data = [{"timeslot":"7pm-8pm","Monday":60,"Tuesday":55},{"timeslot":"8pm-9pm","Monday":70,"Tuesday":60},{"timeslot":"9pm-10pm","Monday":40,"Tuesday":37}];
var result = {};
data.map(function (each) {
Object.keys(each).map(function (key){
result[key] = result[key] || [];
result[key].push(each[key]);
});
});
console.log(result);
这篇关于如何迭代对象数组并按其键名对属性值进行分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!