Line | |
---|
1 | /*exported getData, isObject, mergeDeep */ |
---|
2 | 'use strict'; |
---|
3 | |
---|
4 | var getData = getData || function(id, clear = true) { |
---|
5 | let data = {}; |
---|
6 | // Read the JSON-formatted data from the DOM. (from https://mathiasbynens.be/notes/json-dom-csp) |
---|
7 | // To be use with: <script type="application/json" id="myid-data">{"key":value, …}</script> |
---|
8 | const element = document.getElementById(`${id}-data`); |
---|
9 | if (element) { |
---|
10 | try { |
---|
11 | data = JSON.parse(element.textContent); |
---|
12 | if (clear) { |
---|
13 | // Clear the element’s contents |
---|
14 | element.innerHTML = ''; |
---|
15 | } |
---|
16 | } catch (e) {} |
---|
17 | } |
---|
18 | return data; |
---|
19 | }; |
---|
20 | |
---|
21 | var isObject = isObject || function isObject(item) { |
---|
22 | return (item && typeof item === 'object' && !Array.isArray(item)); |
---|
23 | }; |
---|
24 | |
---|
25 | /** |
---|
26 | * Deep merge two objects. |
---|
27 | * @param target |
---|
28 | * @param ...sources |
---|
29 | */ |
---|
30 | var mergeDeep = mergeDeep || function mergeDeep(target, ...sources) { |
---|
31 | if (!sources.length) return target; |
---|
32 | const source = sources.shift(); |
---|
33 | if (isObject(target) && isObject(source)) { |
---|
34 | for (const key in source) { |
---|
35 | if (isObject(source[key])) { |
---|
36 | if (!target[key]) Object.assign(target, { [key]: {} }); |
---|
37 | mergeDeep(target[key], source[key]); |
---|
38 | } else { |
---|
39 | Object.assign(target, { [key]: source[key] }); |
---|
40 | } |
---|
41 | } |
---|
42 | } |
---|
43 | return mergeDeep(target, ...sources); |
---|
44 | }; |
---|
Note: See
TracBrowser
for help on using the repository browser.