我有一个名为 data 的对象数组,如下所示:
data = [{"timeslot":"7pm-8pm","Monday":60,"Tuesday":55},
{"timeslot":"8pm-9pm","Monday":70,"Tuesday":60},
{"timeslot":"9pm-10pm","Monday":40,"Tuesday":37}]
我想从这个数组中获得三个新数组,如下所示:
timeslot = ["7pm-8pm", "8pm-9pm", "9pm-10pm"]
monday = [60, 70, 40]
tuesdat = [55, 60, 37]
通过它们所属的 data 属性名称对数据值进行有效分组。
这是我的 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中的代码正在用当前元素替换新数组的前一个元素。新数组每个只包含一个元素,而不是所需的三个元素。
我该如何解决这个问题?
答案 0 :(得分:1)
您的代码存在的问题是,当您在keys
数组上进行迭代时,每次都在替换以前的值
result[key.toLowerCase()] = [obj[key]]; // This is replacing the existing value
要向数组添加新条目,您可以使用Array.push()方法,如下所示:
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);
答案 1 :(得分:1)
Basicall你用新数组覆盖最后一个结果
result[key.toLowerCase()] = [obj[key]];
// ^^^^^^^^^^^^^^^^^^^^^^ ^ ^
但是你只需要一个数组用于一个键并推送实际值,比如
result[key] = result[key] || []; // create array, if not exist
result[key].push(o[k]); // push value
工作代码:
var data = [{ timeslot: "7pm-8pm", Monday: 60, Tuesday: 55 }, { timeslot: "8pm-9pm", Monday: 70, Tuesday: 60}, { timeslot: "9pm-10pm", Monday: 40, Tuesday: 37 }],
result = {};
data.forEach(function (o) {
Object.keys(o).forEach(function (k) {
var key = k.toLowerCase();
result[key] = result[key] || [];
result[key].push(o[k]);
});
});
console.log(result);
&#13;