0

How to create a javascript function that will receive a JSON-like object as parameter, like this:

function foo() {
    //handle args somehow
}

And then be able to call it like this:

var someObj = {
    arg1: "some",
    arg2: "thing",
    options: {
        opt1: "asd",
        opt2: false
    }
}

foo(someObj);

Also, how to treat parameters that are not sent to the function (opt2 is omitted in this case):

var someObj = {
    arg1: "some",
    arg2: "thing",
    options: {
        opt1: "asd",
        //opt2: false
    }
}

foo(someObj);

Thanks.

2
  • 1
    Maybe I didn't knew how to search for it beacause I couldn't find it.. Commented Feb 7, 2020 at 17:14
  • 2
    It's not "JSON-like". It's just an object. Access it like you would any other object. Commented Feb 7, 2020 at 17:17

3 Answers 3

2

Your question has nothing to do with JSON. These are regular JavaScript object literals.

The normal thing to do, if your function is expecting parameters, is to define your function as such:

function foo(obj) {

}

From there, you can access the properties of that object like any other.

function foo(obj) {
  console.log(obj.options.opt1);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Define function like below:

 function foo(obj) {
        //handle args somehow
    }

and then use it foo(someObj) where someObj is your json.

if a property is missing in your object, then you handle it as :

if (obj.options.opt2)
{
    console.log('opt2 is available');
} 
else
{
    console.log('opt2 is not available');
} 

Comments

0

If you need to process the argument object like removing the keys which values are false, Then you can use the following method foo which takes object and returns object after removal.

const foo = obj => ({
  ...obj,
  options: Object.fromEntries(
    Object.entries(obj.options).filter(([, value]) => value)
  )
});

var someObj = {
  arg1: "some",
  arg2: "thing",
  options: {
    opt1: "asd",
    opt2: false
  }
};

console.log(foo(someObj));

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.