From df64d3ea382c07e66bc7cc8877ee430206c31d63 Mon Sep 17 00:00:00 2001 From: newracket Date: Mon, 25 Apr 2022 15:45:52 -0700 Subject: [PATCH] fix(Util): flatten ignoring certain fields (#7773) --- packages/discord.js/src/util/Util.js | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/packages/discord.js/src/util/Util.js b/packages/discord.js/src/util/Util.js index 4fbe704bf..0d1da9962 100644 --- a/packages/discord.js/src/util/Util.js +++ b/packages/discord.js/src/util/Util.js @@ -36,15 +36,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; }