Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a param to build a JSON object

How can I pass the subCategory in as an parameter for the function? I have a working solution just passing in the param and then having a switch do the work to make the JSON.subcategory read from the right place. However I feel like there is some thing I am missing on making this more functional, or OO friendly.

So is there a way to make the passed param understand its a variable and not the object literal.

json = {
  weather: ["rain", "snow","sun"],
  news: ["events", "local","world"]
}

messageBuilder(weather)

function messageBuilder(passedVariable){
  var object = json.passedVariable;
  // object = json.weather
  console.log(JSON.stringify(object));
}

Also am I using the terms correctly? I tried to search google for an answer and ended up not really finding anything.

like image 903
whatkai Avatar asked Mar 18 '26 23:03

whatkai


1 Answers

Just pass the object property key name (sub category) in as a string and use bracket notation to pick it from the data in the function.

Note: that's an object, not JSON, so I've named it as such in the example.

const obj = {
  weather: ["rain", "snow", "sun"],
  news: ["events", "local", "world"]
};

messageBuilder('weather');

function messageBuilder(subCat){
  var object = obj[subCat];
  console.log(JSON.stringify(object));
}
like image 127
Andy Avatar answered Mar 20 '26 13:03

Andy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!