diff --git a/index.html b/index.html index 1f0acc0..ccfb316 100644 --- a/index.html +++ b/index.html @@ -27,5 +27,6 @@ Link 5 + Link 6 diff --git a/src/index.js b/src/index.js index d5eb595..9e2cff6 100644 --- a/src/index.js +++ b/src/index.js @@ -267,7 +267,9 @@ function presence(str) { function cleanObject(obj) { for (const key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { - if (obj[key] === null) { + const value = obj[key]; + + if (value === null || isLiteralObject(value) && isEmpty(value)) { delete obj[key]; } } @@ -275,13 +277,36 @@ function cleanObject(obj) { return obj; } +function isLiteralObject(obj) { + return (!!obj) && (obj.constructor === Object); +} + +function getDatasetInKebabCase(element) { + const datasetInKebabCase = {}; + + for (const attrName in element.attributes) { + if (Object.prototype.hasOwnProperty.call(element.attributes, attrName)) { + const attr = element.attributes[attrName]; + + if (attr.name.startsWith('data-')) { + const keyWithoutDataPrefix = attr.name.replace('data-', ''); + + datasetInKebabCase[keyWithoutDataPrefix] = attr.value; + } + } + } + + return datasetInKebabCase; +} + function eventProperties() { return cleanObject({ tag: this.tagName.toLowerCase(), id: presence(this.id), "class": presence(this.className), page: page(), - section: getClosest(this, "data-section") + section: getClosest(this, "data-section"), + data: getDatasetInKebabCase(this) }); }