-1

I am trying to create some objects to store information on how to map an incoming object (from json) to a specific representation, and I use code that looks something like the following:

LocationMap = {
    fields: {
        "name": ValueMap(),
        //"parentLocation": ModelMap(LocationMap),
    }
}

PersonMap = {
    fields: {
        "name": ValueMap(),
        "location": ModelMap(LocationMap),
    }
}

The MapValue and MapModel functions can be thought of as returning functions which act on the incoming value to map it to a new value.

The trouble I'm having is with the commented out line, where I need the Location object to recursively reference itself, which is of course impossible. If these were classes in another language I think there could be a recursive reference. How can I accomplish the same thing with JavaScript?

I made a small working example on jsfiddle.

1 Answers1

0

If these were classes in another language I think there could be a recursive reference

These are objects, not classes. The problem you are having is you are not used to anonymous classes or object literals. The solution is simple, make them classes:

class LocationMap {
  constructor () {
    this.fields = {
      name: valueMap(),
      location: modelMap(this)
    };
  }
}

class PersonMap = {
  constructor () {
    this.fields = {
      name: valueMap(),
      location: modelMap(locationMap)
    };
  }
}

var locationMap = new LocationMap();
var personMap = new PersonMap();

if you're running in an environment that doesn't support ES6 syntax then you can use the old-school syntax:

function LocationMap () {
  this.fields = {
    name: valueMap(),
    location: modelMap(this)
  };
}

function PersonMap () {
  this.fields = {
    name: valueMap(),
    location: modelMap(locationMap)
  };
}

var locationMap = new LocationMap();
var personMap = new PersonMap();

You can also manually construct the objects:

var locationMap = {};
locationMap.fields = {};
locationMap.fields.name = valueMap();
locationMap.fields.location = modelMap(locationMap);

var personMap = {};
locationMap.fields = {};
locationMap.fields.name = valueMap();
locationMap.fields.location = modelMap(locationMap);
slebetman
  • 109,858
  • 19
  • 140
  • 171