UNPKG

getdomdata

Version:

get dom data to object

6 lines (5 loc) 1.03 kB
/*! * getdomdata v0.0.3 * https://github.com/lemon3/getdomdata */ (function(n,a){typeof exports=="object"&&typeof module!="undefined"?module.exports=a():typeof define=="function"&&define.amd?define(a):(n=typeof globalThis!="undefined"?globalThis:n||self,n.getDomData=a())})(this,function(){"use strict";const n=e=>e&&typeof e=="object",a=(...e)=>{const r={};let o,t;return e.forEach(s=>{for(let c in s)o=r[c],t=s[c],Array.isArray(o)&&Array.isArray(t)?r[c]=o.concat(...t):n(o)&&n(t)?r[c]=a(o,t):r[c]=t}),r},p=e=>{e=e.replace(/[\\ \t\n\r'"]/gm,"").replace(/(\w+)/gi,'"$1"'),e[0]!=="{"&&(e=`{${e}}`);try{return JSON.parse(e)}catch(r){return!1}},l=e=>{if(!e.match(/[^\w]+/i))return e;e=e.replace(/'/g,'"');try{return JSON.parse(e)}catch(r){return p(e)}};return(e,r)=>{if(!e||typeof e!="object")return!1;let o={};return e.getAttributeNames().filter(t=>t.substr(0,5)==="data-").forEach(t=>{const s=t.substr(5).split("-"),c=s.length,y=e.getAttribute(t),u={};let f=u;s.forEach((i,d)=>{f[i]=c-1!==d?{}:l(y),f=f[i]}),o=a(o,u)}),r?o[r]:o}});