whatkai
whatkai

Reputation: 179

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.

Upvotes: 4

Views: 1313

Answers (2)

Andy
Andy

Reputation: 63550

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

Upvotes: 1

Mircea Andrei
Mircea Andrei

Reputation: 78

Just modify your code a little bit:

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

        }

        messageBuilder('weather');

        function messageBuilder(passedVariable){

        var object = json[passedVariable];
             // object = json.weather
            console.log(object);

        }

First of all you should pass your parameter as a string. Then just pull out the property from the object using object['property']

Upvotes: 0

Related Questions