Skip to content

tags: - examples - objects - properties - tutorial


Object Manipulation

This guide demonstrates working with objects in EverSharp, including creating objects, accessing properties, dynamic property access, nested structures, and object transformation.

Creating Objects

Object Literals

// Simple object
person = {
  name: "John Smith",
  age: 35,
  email: "john@example.com",
};

// Object with various data types
policy = {
  id: 12345,
  effectiveDate: $ToDate("2024-01-01"),
  premium: 1200.0,
  isActive: true,
  holder: null,
};

// Empty object
empty = {};

Nested Objects

customer = {
  id: 1001,
  name: "Alice Johnson",
  contact: {
    email: "alice@example.com",
    phone: "555-1234",
    address: {
      street: "123 Main St",
      city: "Springfield",
      zip: "12345",
    },
  },
  preferences: {
    newsletter: true,
    notifications: false,
  },
};

Accessing Properties

Dot Notation

person = {
  name: "John Smith",
  age: 35,
  email: "john@example.com",
};

// Access properties
personName = person.name; // "John Smith"
personAge = person.age; // 35
personEmail = person.email; // "john@example.com"

Nested Property Access

customer = {
  name: "Alice",
  address: {
    city: "Springfield",
    zip: "12345",
  },
};

// Access nested properties
city = customer.address.city; // "Springfield"
zip = customer.address.zip; // "12345"

Dynamic Property Access

Using $GetValue

Access properties by name (useful when property name is in a variable):

person = {
  firstName: "John",
  lastName: "Smith",
  age: 35,
};

// Get property by name
fieldName = "firstName";
value = $GetValue(person, fieldName); // "John"

// Different field
fieldName = "age";
value = $GetValue(person, fieldName); // 35

Using $SetValue

Set property values dynamically:

person = {
  name: "John",
  age: 35,
};

// Set property by name
$SetValue(person, "age", 36);
// person.age is now 36

// Add new property
$SetValue(person, "email", "john@example.com");
// person now has: { name: "John", age: 36, email: "john@example.com" }

Adding Properties with .AddProperty()

person = {
  name: "John",
  age: 35,
};

// Add a new property
person.AddProperty("email", "john@example.com");
// person now has: { name: "John", age: 35, email: "john@example.com" }

// Add multiple properties
person.AddProperty("phone", "555-1234");
person.AddProperty("city", "Springfield");

Working with Arrays of Objects

Creating Arrays of Objects

policies = [
  {
    id: 1,
    premium: 1200,
    status: "Active",
    effectiveDate: $ToDate("2024-01-01"),
  },
  {
    id: 2,
    premium: 850,
    status: "Pending",
    effectiveDate: $ToDate("2024-02-15"),
  },
  {
    id: 3,
    premium: 1500,
    status: "Active",
    effectiveDate: $ToDate("2024-01-10"),
  },
];

Filtering Objects

// Get active policies
active = policies.Filter((p) => p.status == "Active");

// Get high-premium policies
expensive = policies.Filter((p) => p.premium >= 1000);

// Multiple conditions
activeExpensive = policies.Filter(
  (p) => p.status == "Active" && p.premium >= 1000
);

Extracting Property Values

// Get all premiums
premiums = policies.Map((p) => p.premium);
// Result: [1200, 850, 1500]

// Get all IDs
ids = policies.Map((p) => p.id);
// Result: [1, 2, 3]

Transforming Objects

// Create summary objects
summaries = policies.Map((p) => {
  return {
    policyNumber: p.id,
    monthlyPremium: p.premium / 12,
    isActive: p.status == "Active",
  };
});

// Result: [
//   { policyNumber: 1, monthlyPremium: 100, isActive: true },
//   { policyNumber: 2, monthlyPremium: 70.83, isActive: false },
//   { policyNumber: 3, monthlyPremium: 125, isActive: true }
// ]

Practical Examples

Example 1: Build Object from Properties

buildCustomer = function (id, name, email, age) {
  customer = {};
  customer.AddProperty("id", id);
  customer.AddProperty("name", name);
  customer.AddProperty("email", email);
  customer.AddProperty("age", age);
  customer.AddProperty("createdDate", $Now());

  return customer;
};

newCustomer = buildCustomer(1001, "Alice", "alice@example.com", 28);

// Result: {
//   id: 1001,
//   name: "Alice",
//   email: "alice@example.com",
//   age: 28,
//   createdDate: 2024-11-28 14:30:00
// }

Example 2: Merge Objects

Combine properties from multiple objects:

mergeObjects = function (obj1, obj2) {
  result = {};

  // Copy properties from obj1
  // (Note: In practice, you'd need to know property names
  // or use a more complex approach)

  // Simplified example with known properties
  result.AddProperty("id", obj1.id);
  result.AddProperty("name", obj1.name);
  result.AddProperty("email", obj2.email);
  result.AddProperty("phone", obj2.phone);

  return result;
};

personal = { id: 1, name: "John" };
contact = { email: "john@example.com", phone: "555-1234" };

merged = mergeObjects(personal, contact);
// Result: { id: 1, name: "John", email: "john@example.com", phone: "555-1234" }

Example 3: Calculate Derived Properties

policies = [
  { id: 1, annualPremium: 1200, term: 12 },
  { id: 2, annualPremium: 2400, term: 24 },
  { id: 3, annualPremium: 1800, term: 12 },
];

// Add monthly premium calculation
enhanced = policies.Map((p) => {
  monthly = p.annualPremium / 12;
  total = p.annualPremium * (p.term / 12);

  return {
    id: p.id,
    annualPremium: p.annualPremium,
    monthlyPremium: monthly,
    termMonths: p.term,
    totalPremium: total,
  };
});

// Result: [
//   { id: 1, annualPremium: 1200, monthlyPremium: 100, termMonths: 12, totalPremium: 1200 },
//   { id: 2, annualPremium: 2400, monthlyPremium: 200, termMonths: 24, totalPremium: 4800 },
//   { id: 3, annualPremium: 1800, monthlyPremium: 150, termMonths: 12, totalPremium: 1800 }
// ]

Example 4: Group Objects by Property

transactions = [
  { type: "Premium", amount: 1200, month: "Jan" },
  { type: "Claim", amount: 500, month: "Jan" },
  { type: "Premium", amount: 1200, month: "Feb" },
  { type: "Claim", amount: 750, month: "Feb" },
  { type: "Premium", amount: 1200, month: "Mar" },
];

// Group by type and calculate totals
summary = transactions.Reduce(
  (acc, t) => {
    if (t.type == "Premium") {
      acc.premiumCount = acc.premiumCount + 1;
      acc.premiumTotal = acc.premiumTotal + t.amount;
    } else {
      acc.claimCount = acc.claimCount + 1;
      acc.claimTotal = acc.claimTotal + t.amount;
    }
    return acc;
  },
  {
    premiumCount: 0,
    premiumTotal: 0,
    claimCount: 0,
    claimTotal: 0,
  }
);

// Result: {
//   premiumCount: 3,
//   premiumTotal: 3600,
//   claimCount: 2,
//   claimTotal: 1250
// }

Example 5: Validate Object Properties

validatePolicy = function (policy) {
  errors = [];

  // Check required fields
  if ($GetValue(policy, "id") == null) {
    errors.Push("Missing policy ID");
  }

  if ($GetValue(policy, "premium") == null) {
    errors.Push("Missing premium amount");
  } else if (policy.premium <= 0) {
    errors.Push("Premium must be greater than zero");
  }

  if ($GetValue(policy, "effectiveDate") == null) {
    errors.Push("Missing effective date");
  }

  // Return validation result
  return {
    isValid: errors.Length == 0,
    errors: errors,
  };
};

policy1 = { id: 1, premium: 1200, effectiveDate: $ToDate("2024-01-01") };
policy2 = { id: 2, premium: -500 };

result1 = validatePolicy(policy1);
// Result: { isValid: true, errors: [] }

result2 = validatePolicy(policy2);
// Result: { isValid: false, errors: ["Premium must be greater than zero", "Missing effective date"] }

Example 6: Clone Object with Modifications

cloneWithChanges = function (original, changes) {
  // Create new object with original properties
  clone = {
    id: original.id,
    name: original.name,
    premium: original.premium,
    status: original.status,
  };

  // Apply changes
  if ($GetValue(changes, "premium") != null) {
    clone.premium = changes.premium;
  }

  if ($GetValue(changes, "status") != null) {
    clone.status = changes.status;
  }

  return clone;
};

original = {
  id: 1,
  name: "Policy A",
  premium: 1200,
  status: "Active",
};

updated = cloneWithChanges(original, {
  premium: 1350,
  status: "Pending",
});

// original: { id: 1, name: "Policy A", premium: 1200, status: "Active" }
// updated: { id: 1, name: "Policy A", premium: 1350, status: "Pending" }

Example 7: Enrich Objects with External Data

policies = [
  { id: 1, customerId: 101, premium: 1200 },
  { id: 2, customerId: 102, premium: 850 },
  { id: 3, customerId: 101, premium: 1500 },
];

customers = [
  { id: 101, name: "Alice Johnson", tier: "Gold" },
  { id: 102, name: "Bob Smith", tier: "Silver" },
];

// Add customer information to policies
enriched = policies.Map((policy) => {
  // Find matching customer
  customer = customers.Find((c) => c.id == policy.customerId);

  return {
    policyId: policy.id,
    premium: policy.premium,
    customerId: policy.customerId,
    customerName: customer.name,
    customerTier: customer.tier,
  };
});

// Result: [
//   { policyId: 1, premium: 1200, customerId: 101, customerName: "Alice Johnson", customerTier: "Gold" },
//   { policyId: 2, premium: 850, customerId: 102, customerName: "Bob Smith", customerTier: "Silver" },
//   { policyId: 3, premium: 1500, customerId: 101, customerName: "Alice Johnson", customerTier: "Gold" }
// ]

Example 8: Conditional Property Addition

createPolicyObject = function (id, premium, isRenewal) {
  policy = {
    id: id,
    premium: premium,
    effectiveDate: $Today(),
  };

  // Add renewal-specific properties
  if (isRenewal) {
    policy.AddProperty("renewalDiscount", premium * 0.1);
    policy.AddProperty("finalPremium", premium * 0.9);
    policy.AddProperty("isRenewal", true);
  } else {
    policy.AddProperty("finalPremium", premium);
    policy.AddProperty("isRenewal", false);
  }

  return policy;
};

newPolicy = createPolicyObject(1, 1000, false);
// { id: 1, premium: 1000, effectiveDate: 2024-11-28, finalPremium: 1000, isRenewal: false }

renewalPolicy = createPolicyObject(2, 1000, true);
// { id: 2, premium: 1000, effectiveDate: 2024-11-28, renewalDiscount: 100, finalPremium: 900, isRenewal: true }

Example 9: Aggregate Object Properties

policies = [
  { id: 1, premium: 1200, claims: 0 },
  { id: 2, premium: 850, claims: 2 },
  { id: 3, premium: 1500, claims: 1 },
  { id: 4, premium: 950, claims: 0 },
];

// Calculate portfolio statistics
portfolio = policies.Reduce(
  (acc, p) => {
    acc.totalPolicies = acc.totalPolicies + 1;
    acc.totalPremium = acc.totalPremium + p.premium;
    acc.totalClaims = acc.totalClaims + p.claims;

    if (p.claims > 0) {
      acc.policiesWithClaims = acc.policiesWithClaims + 1;
    }

    if (p.premium > acc.highestPremium) {
      acc.highestPremium = p.premium;
    }

    return acc;
  },
  {
    totalPolicies: 0,
    totalPremium: 0,
    totalClaims: 0,
    policiesWithClaims: 0,
    highestPremium: 0,
  }
);

// Calculate average
portfolio.AddProperty(
  "averagePremium",
  portfolio.totalPremium / portfolio.totalPolicies
);

// Result: {
//   totalPolicies: 4,
//   totalPremium: 4500,
//   totalClaims: 3,
//   policiesWithClaims: 2,
//   highestPremium: 1500,
//   averagePremium: 1125
// }

Example 10: Dynamic Field Access

// Get field value based on configuration
getFieldValue = function (object, fieldConfig) {
  fieldName = fieldConfig.name;
  value = $GetValue(object, fieldName);

  // Apply transformation if specified
  if (fieldConfig.transform == "uppercase") {
    value = value.ToUpper();
  } else if (fieldConfig.transform == "currency") {
    value = "$" + value.ToString("N2");
  }

  return value;
};

policy = {
  id: 1,
  holderName: "john smith",
  premium: 1250.5,
};

// Get name in uppercase
nameConfig = { name: "holderName", transform: "uppercase" };
holderName = getFieldValue(policy, nameConfig);
// Result: "JOHN SMITH"

// Get premium formatted as currency
premiumConfig = { name: "premium", transform: "currency" };
premiumDisplay = getFieldValue(policy, premiumConfig);
// Result: "$1,250.50"

Common Patterns

Default Values

// Provide default value if property is missing
getWithDefault = function (object, propertyName, defaultValue) {
  value = $GetValue(object, propertyName);

  if (value == null) {
    return defaultValue;
  } else {
    return value;
  }
};

config = { timeout: 30 };

timeout = getWithDefault(config, "timeout", 60); // 30 (exists)
retries = getWithDefault(config, "retries", 3); // 3 (default)

Check Property Exists

hasProperty = function (object, propertyName) {
  value = $GetValue(object, propertyName);
  return value != null;
};

person = { name: "John", age: 35 };

hasName = hasProperty(person, "name"); // true
hasEmail = hasProperty(person, "email"); // false

Object Builder Pattern

createPolicyBuilder = function () {
  policy = {};

  return {
    policy: policy,

    withId: function (id) {
      policy.AddProperty("id", id);
      return this;
    },

    withPremium: function (amount) {
      policy.AddProperty("premium", amount);
      return this;
    },

    withHolder: function (name) {
      policy.AddProperty("holderName", name);
      return this;
    },

    build: function () {
      return policy;
    },
  };
};

// Note: This pattern is conceptual - EverSharp doesn't support
// method chaining directly. In practice, you'd use functions:

createPolicy = function (id, premium, holderName) {
  policy = {};
  policy.AddProperty("id", id);
  policy.AddProperty("premium", premium);
  policy.AddProperty("holderName", holderName);
  policy.AddProperty("createdDate", $Now());
  return policy;
};

newPolicy = createPolicy(1, 1200, "John Smith");

Object Comparison

// Check if two objects have the same property values
objectsEqual = function (obj1, obj2, properties) {
  allMatch = true;
  index = 0;

  while (index < properties.Length && allMatch) {
    prop = properties[index];
    val1 = $GetValue(obj1, prop);
    val2 = $GetValue(obj2, prop);

    if (val1 != val2) {
      allMatch = false;
    }

    index = index + 1;
  }

  return allMatch;
};

obj1 = { id: 1, name: "Alice", age: 30 };
obj2 = { id: 1, name: "Alice", age: 30 };
obj3 = { id: 1, name: "Bob", age: 30 };

equal1 = objectsEqual(obj1, obj2, ["id", "name", "age"]); // true
equal2 = objectsEqual(obj1, obj3, ["id", "name", "age"]); // false

Best Practices

Use Consistent Property Names

// Good: consistent naming
customer1 = { firstName: "John", lastName: "Smith" };
customer2 = { firstName: "Alice", lastName: "Johnson" };

// Avoid: inconsistent naming
// customer1 = { firstName: "John", lastName: "Smith" };
// customer2 = { first: "Alice", last: "Johnson" };  // Different property names

Validate Before Access

// Check if property exists before accessing nested properties
getSafely = function (object, property) {
  if (object == null) {
    return null;
  }

  value = $GetValue(object, property);
  return value;
};

customer = { name: "John" };
email = getSafely(customer, "email"); // null (doesn't throw error)

Create New Objects for Transformations

// Don't modify original objects
// Instead, create new objects with changes

// Good: create new object
updated = {
  id: original.id,
  name: original.name,
  premium: original.premium * 1.1, // 10% increase
};

// Avoid modifying original:
// original.premium = original.premium * 1.10;

Next Steps

See Also