diff --git a/src/util/Util.js b/src/util/Util.js index 47e55d3..968f720 100644 --- a/src/util/Util.js +++ b/src/util/Util.js @@ -42,15 +42,20 @@ class Util extends null { const element = obj[prop]; const elemIsObj = isObject(element); const valueOf = elemIsObj && typeof element.valueOf === 'function' ? element.valueOf() : null; + const hasToJSON = elemIsObj && typeof element.toJSON === 'function'; // If it's a Collection, make the array of keys if (element instanceof Collection) out[newProp] = Array.from(element.keys()); // If the valueOf is a Collection, use its array of keys else if (valueOf instanceof Collection) out[newProp] = Array.from(valueOf.keys()); - // If it's an array, flatten each element - else if (Array.isArray(element)) out[newProp] = element.map(e => Util.flatten(e)); + // If it's an array, call toJSON function on each element if present, otherwise flatten each element + else if (Array.isArray(element)) out[newProp] = element.map(e => e.toJSON?.() ?? Util.flatten(e)); // If it's an object with a primitive `valueOf`, use that value else if (typeof valueOf !== 'object') out[newProp] = valueOf; + // If it's an object with a toJSON function, use the return value of it + else if (hasToJSON) out[newProp] = element.toJSON(); + // If element is an object, use the flattened version of it + else if (typeof element === 'object') out[newProp] = Util.flatten(element); // If it's a primitive else if (!elemIsObj) out[newProp] = element; }