0

I want to be able to create a series of objects in JSON like this:

const objects = {
  type1: {
    inputs: [value1, resultOfFunction(), value3],
    typeFunction: (arg1, arg2, arg3) => {
      //this does a thing with the inputs and returns an output
    }
  },
  type2: {
    inputs: [val1, val2],
    typeFunction: (arg1, arg2) => {
      //this does a thing with these inputs and returns an output
    }
  }
}

The point here is that each type contains some kind of blackbox function that takes a series of arguments and returns a value. The number of arguments will differ with each type, as will the values of those arguments. I have suggested there is an array inputs that specifies what values are to be passed into each function, but I am open to alternatives.

How can I then generically call these functions with their respective inputs? e.g.

type1.typeFunction() //obvs this doesn't work
1
  • 1
    That's not JSON. JSON is a textual notation for data exchange. (More) If you're dealing with JavaScript source code, and not dealing with a string, you're not dealing with JSON. Commented Dec 11, 2016 at 15:53

1 Answer 1

2

How can I then generically call these functions with their respective inputs?

You either specify the inputs, perhaps using spread notation:

type1.typeFunction(...type1.inputs);

...or you define a function on the type that does that.


Note: In

inputs: [value1, resultOfFunction(), value3]

resultOfFunction will be called as of when that overall object initializer is processed, not later when type1.typeFunction is called. Maybe that's what you want, but I thought it was useful to call it out specifically. If it isn't what you want, then you have to put that in a function so it's not done until/unless that function is called.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.