From 4ec3355961b7105a417e8854ae72f4ee302690f9 Mon Sep 17 00:00:00 2001 From: Almeida Date: Fri, 16 Dec 2022 13:13:43 +0000 Subject: [PATCH] fix(Util): flatten ignoring certain fields (v13) (#8936) Fixes https://github.com/discordjs/discord.js/issues/8929 --- src/util/Util.js | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/util/Util.js b/src/util/Util.js index e830e3150ecd..eb1a1dfe15eb 100644 --- a/src/util/Util.js +++ b/src/util/Util.js @@ -41,15 +41,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; }