我想迭代一个对象的属性,并将每个属性的值推送到一个共享属性名称的数组。
如何使用属性名称动态引用数组名称?
var obj = {"timeslot": "6am-7am", "Monday": "5", "Tuesday": "9"};
var timeslot = [];
var monday = [];
var tuesday = [];
Object.keys(obj).forEach(function(key) {
console.log(key); // Returns "timeslot", "Monday", and "Tuesday" respectively
console.log(obj[key]); // Returns "6am-7am", "5" and "9" respectively
});
我想要的结果是三个数组,如下所示:
timeslot = ["6am-7am"];
monday = ["5"];
tuesday = ["9"];
答案 0 :(得分:2)
使用obj
和Object#kays
迭代Array#forEach
。如果变量位于全局范围内,则可以使用[]
对象上的括号表示法window
将其分配给变量。
var obj = { "timeslot": "6am-7am", "Monday": "5", "Tuesday": "9" };
var timeslot = [];
var monday = [];
var tuesday = [];
Object.keys(obj).forEach(function(key) {
window[key.toLowerCase()].push(obj[key]);
});
console.log(timeslot, monday, tuesday);
如果没有,请将数组收集到另一个对象中:
var obj = { "timeslot": "6am-7am", "Monday": "5", "Tuesday": "9" };
var result = {};
Object.keys(obj).forEach(function(key) {
result[key.toLowerCase()] = [obj[key]];
});
console.log(result);
使用ES6,您可以使用Object#assign
和Array#map
进行解构来获取变量:
const obj = { "timeslot": "6am-7am", "Monday": "5", "Tuesday": "9" };
const { timeslot, monday, tuesday } = Object.assign(...Object.keys(obj).map((key) => ({
[key.toLowerCase()]: obj[key]
})));
console.log(timeslot, monday, tuesday);