2

In C#, I can create a class that acts as a user-defined type, such as:

Public Class FullName 
{
  string FirstName;
  string LastName;
}

Public Class Address
{
  string Line1;
  string Line2;
  string City;
  string State;
  string Zip;
}

and then I can create:

Public Class Person
{
  FullName Name;
  Address HomeAddress;
  Address WorkAddress;
}

This allows me to reference the data like:

Person Bob;
Bob.WorkAddress.Line1 = "123 Sycamore Rd";
Bob.HomeAddress.Line1 = "1313 MockingBird Ln";
Bob.FullName.LastName = "Smith";
etc...

Ultimately, I want to create a 2D array of Person, so I don't want to hardcode (pre-populate?) the data until I know what it is.

I'd like to be able to do the same thing in JavaScript (specifically node.js), but can't seem to find an obvious way of doing so. Is this just fundamentally the wrong approach, or am I just missing something?

  • ES6 has a nice way of defining classes, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes. Also, this answer might be of some use to you, http://stackoverflow.com/a/387733/640263. Take a look at Typescript as well (if you are used to c#), https://www.typescriptlang.org/. – Peter Dempsey May 03 '17 at 20:19
  • It seems like TypeScript might be a good choice if I want to continue doing things strongly typed. Part of this exercise is my own attempt to get better at JavaScript (particularly Node.js) so I think I need to retrain my brain to think accordingly, rather than trying to force the wrong (but more familiar) approach. – Chris G. Williams May 04 '17 at 13:40

2 Answers2

1

In Javascript you can create data objects directly (no classes):

var bob = {
  workAddress: { line1: "123 Sycamore" },
  fullName: { lastName: "Smith" }
};

It's also possible to create a class, but it's usually not necessary for mere data objects.

Ultimately, I want to create a 2D array of Person, so I don't want to hardcode (pre-populate?) the data until I know what it is.

You can create an array and later add persons to it:

var persons = [];
...
persons.push(bob);

For a 2D array, create an array to contain your person arrays:

var persons2D = [];
...
persons2D.push(persons);
Jordão
  • 55,340
  • 13
  • 112
  • 144
0

A really good example of javascript objects and their notation would be JSON.org

Here is an object that has 2 string properties, and a 3rd property which is an array. One slight difference is that because javascript is not strongly typed, the "residents" property could just be a simple string or an array. So you have to be careful when parsing as any property could be either a string or another array.

var household = {
    address: "1234 N 56th st"
    , city: "somewhere"
    , residents: [
        { Name: "My Name" }
        , { Name: "My Alias" }
    ]
};

Now depending on how you are sourcing the data, you can use the javascript or JSON (de)serialize methods within C# to populate.

Mad Myche
  • 1,075
  • 1
  • 7
  • 15