简体   繁体   English

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

[英]How to reference an array dynamically using the name of an object's property

I want to iterate an object's properties, and push the value of each property to an array sharing the property's name. 我想迭代一个对象的属性,并将每个属性的值推送到共享该属性名称的数组中。

How can I reference the array name dynamically using the name of a property? 如何使用属性名称动态引用数组名称?

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
});

The result I want is three arrays, like so: 我想要的结果是三个数组,如下所示:

timeslot = ["6am-7am"];
monday = ["5"];
tuesday = ["9"];

Iterate obj using Object#kays , and Array#forEach . 使用Object#kaysArray#forEach迭代obj If the variables are on the global scope, you can use the brackets notation [] on the window object to assign it to the variables. 如果变量在全局范围内,则可以在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); 

If not, collect the arrays into another object: 如果不是,请将数组收集到另一个对象中:

 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); 

With ES6 you can use destructuring with Object#assign and Array#map to get the variables: 使用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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM