0

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"];
1
  • 1
    window[key] = obj[key] in your forEach loop (that's for global var in browser) Commented Jan 10, 2017 at 23:02

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.