Flatten a record with an array of objects into multiple records

I have a MSCRM export that returns records that contain an array of objects. I would like to flatten the results into multiple records. Transformation has an option to create output rows from an input record, but no option to create output records from input rows. Is this a formatting change that requires JavaScript?

I need to reformat the sample below to output 2 records without any arrays.

Yeah, this requires a pre-save page script to take the 1-record input and return 2 records on output. You could also use one-to-many on all your flow steps, but you may have reasons that won't work for you.

That’s what I suspected. Do you have a quick JavaScript example for that?

Something like this

function preSavePage(options) {
  const out = [];

  (options.data || []).forEach(parent => {
    const children = parent && parent.contact_customer_accounts;

    // If no children array, output nothing for this parent (change if you want a passthrough)
    if (!Array.isArray(children) || children.length === 0) return;

    // Parent copy without the array
    const parentCopy = Object.assign({}, parent);
    delete parentCopy.contact_customer_accounts;

    // One output record per child
    children.forEach(child => {
      out.push(Object.assign({}, child, { _PARENT: parentCopy }));
    });
  });

  return {
    data: out,
    errors: options.errors,
    abort: false,
    newErrorsAndRetryData: []
  };
}

1 Like

Thanks! That worked great!

1 Like