jonmrich
jonmrich

Reputation: 4323

Issue creating an object to send to API

I'm trying to come up with something in this format:

"hours":{
      "<default>":{
        "mon_open_close":[...],
        "tue_open_close":[...],
        "wed_open_close":[...],
        "thu_open_close":[...],
        "fri_open_close":[...],
        "sat_open_close":[...],
        "sun_open_close":[...],
      }
    }

I have a bunch of variables defined like this (one for each day of the week):

var wed_open_close_hours = [operationTime[2].timeFrom+'-'+operationTime[2].timeTill]; 

That yields something like: [10:00-16:00]

And then have this array:

 $all_hours_text = ['mon_open_close', 'tues_open_close' ,'wed_open_close' , 'thu_open_close' , 'fri_open_close' , 'sat_open_close' ,'sun_open_close'];

The issue I have is how to roll it all together and create this one single object. Can someone point me in the right direction?

Upvotes: 1

Views: 32

Answers (1)

Xingzhou Liu
Xingzhou Liu

Reputation: 1559

So if you set

var wed_open_close_hours = [operationTime[2].timeFrom+'-'+operationTime[2].timeTill]; 

in a global scope, it will also be available as

window.wed_open_close_hours;

Otherwise it's available if you did something like eval("wed_open_close_hours"); So you could do

all_hours_text.map(function(varname) {
      if(window[varname+"_hours"]) {

          result["hours"]["<default>"][varname] = window[varname+"_hours"];
      }
})

or

 all_hours_text.map(function(varname) {

          result["hours"]["<default>"][varname] = eval(varname+"_hours");

})

However, neither setting variables at the global scope nor using eval is recommended practice. You really should consider factoring the code to something like:

var output = {}
output.hours = {}
output.hours["<default>"] = {}

.,..
output.hours["<default>"].wed_open_close = [operationTime[2].timeFrom+'-'+operationTime[2].timeTill];    

Upvotes: 1

Related Questions