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
MDalt
  • 1,681
  • 2
  • 24
  • 46
  • 1
    That's not JSON. JSON is a *textual notation* for data exchange. [(More)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. – T.J. Crowder Dec 11 '16 at 15:53

1 Answers1

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875