Accessing parent object values in nested mail merge

Wondering if there’s a way to access parent object values in a nested mail merge? For example

with an object that looks like the following:

{
    Account: {
        Name: "Test"
    },
    InvoiceItems: [
        { itemName: "item1" },
        { itemName: "item2" }
    ]
}

Can I create a mail merge template that looks like this?
{MERGEFIELD RangeStart:InvoiceItems}
{MERGEFIELD Account.Name }
{MERGEFIELD RangeEnd:InvoiceItems}

Right now when I try this the Account.Name merge field just shows as <<Account.Name>> in the resulting document.

Hi Chad,

No, the “Account.Name” value will be searched for inside the “InvoiceItems” object.

Perhaps you could use something like this to search for the specified value in the parent record:

// Customize mail merge.
document.MailMerge.FieldMerging += (sender, e) =>
{
    if (e.IsValueFound)
        return;

    string[] names = e.FieldName.Split('.');
    object source = e.MergeContext.ParentContext?.Record;

    foreach (string name in names)
    {
        if (source == null)
            return;

        var property = source.GetType().GetProperty(name);
        source = property.GetValue(source);
    }

    if (source != null)
    {
        e.Inline = new Run(e.Document, source.ToString()) { CharacterFormat = e.Field.CharacterFormat.Clone() };
        e.Cancel = false;
    }
};

// Execute mail merge.
document.MailMerge.Execute(myDataSource);

Does this work for you?

Regards,
Mario