Callum
Callum

Reputation: 313

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

Upvotes: 0

Views: 37

Answers (1)

Ori Drori
Ori Drori

Reputation: 191976

Iterate obj using Object#kays, and Array#forEach. If the variables are on the global scope, you can use the brackets notation [] on the window object to assign it to the variables.

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:

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

Upvotes: 2

Related Questions