如何使用对象属性的名称动态引用数组

时间:2017-01-10 23:01:39

标签: javascript arrays javascript-objects

我想迭代一个对象的属性,并将每个属性的值推送到一个共享属性名称的数组。

如何使用属性名称动态引用数组名称?

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"];

1 个答案:

答案 0 :(得分:2)

使用objObject#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#assignArray#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);