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 = person.AddProperty("email", "john@example.com");
// person now has: { name: "John", age: 35, email: "john@example.com" }
// Add multiple properties
person = person.AddProperty("phone", "555-1234");
person = 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¶
function buildCustomer(id, name, email, age) {
customer = {};
customer = customer.AddProperty("id", id);
customer = customer.AddProperty("name", name);
customer = customer.AddProperty("email", email);
customer = customer.AddProperty("age", age);
customer = 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:
function mergeObjects(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 = result.AddProperty("id", obj1.id);
result = result.AddProperty("name", obj1.name);
result = result.AddProperty("email", obj2.email);
result = 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 = { "premiumCount": 0, "premiumTotal": 0, "claimCount": 0, "claimTotal": 0 };
transactions.ForEach((t) => {
if (t.type == "Premium") {
summary.premiumCount = summary.premiumCount + 1;
summary.premiumTotal = summary.premiumTotal + t.amount;
} else {
summary.claimCount = summary.claimCount + 1;
summary.claimTotal = summary.claimTotal + t.amount;
}
});
// Result: {
// premiumCount: 3,
// premiumTotal: 3600,
// claimCount: 2,
// claimTotal: 1250
// }
Example 5: Validate Object Properties¶
function validatePolicy(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¶
function cloneWithChanges(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¶
function createPolicyObject(id, premium, isRenewal) {
policy = {
"id": id,
"premium": premium,
"effectiveDate": $Today()
};
// Add renewal-specific properties
if (isRenewal) {
policy = policy.AddProperty("renewalDiscount", premium * 0.1);
policy = policy.AddProperty("finalPremium", premium * 0.9);
policy = policy.AddProperty("isRenewal", true);
} else {
policy = policy.AddProperty("finalPremium", premium);
policy = 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 = { "totalPolicies": 0, "totalPremium": 0, "totalClaims": 0, "policiesWithClaims": 0, "highestPremium": 0 };
policies.ForEach((p) => {
portfolio.totalPolicies = portfolio.totalPolicies + 1;
portfolio.totalPremium = portfolio.totalPremium + p.premium;
portfolio.totalClaims = portfolio.totalClaims + p.claims;
if (p.claims > 0) {
portfolio.policiesWithClaims = portfolio.policiesWithClaims + 1;
}
if (p.premium > portfolio.highestPremium) {
portfolio.highestPremium = p.premium;
}
});
// Calculate average
portfolio = 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
function getFieldValue(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
function getWithDefault(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¶
person = { "name": "John", "age": 35, "email": null };
hasName = person.HasProperty("name"); // true
hasEmail = person.HasProperty("email"); // true
hasPhone = $HasProperty(person, "phone"); // false
// Use this only when you specifically need a non-null value
email = $GetValue(person, "email");
hasNonNullEmail = email != null; // false
Object Builder Pattern¶
// EverSharp objects can't hold functions, so a fluent builder isn't possible.
// Use a function that builds the object instead:
function createPolicy(id, premium, holderName) {
policy = {};
policy = policy.AddProperty("id", id);
policy = policy.AddProperty("premium", premium);
policy = policy.AddProperty("holderName", holderName);
policy = policy.AddProperty("createdDate", $Now());
return policy;
}
newPolicy = createPolicy(1, 1200, "John Smith");
Object Comparison¶
// Check if two objects have the same property values
function objectsEqual(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
function getSafely(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¶
- Business Rules - Complex calculations using objects
- Array Operations - Working with arrays of objects
- Working with Dates - Date properties in objects
See Also¶
- Objects Data Type - Object fundamentals
- Utility Functions - $GetValue, $SetValue, .AddProperty()
- Lambda Expressions - Transforming objects with lambdas