UNPKG

merge-jsons

Version:

merg-jsons allows you to merge json, removing duplicate objects

75 lines (60 loc) 2.02 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.mergeJSON = exports.isJSON = exports.removeDuplicateJSON = undefined; var _stringify = require("babel-runtime/core-js/json/stringify"); var _stringify2 = _interopRequireDefault(_stringify); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // 'use strict'; // JSON constructor for checking an object is JSON or not let jsonC = {}.constructor; const isJSON = function isJSON(json) { if (json && json.constructor === jsonC) { return true; } else { return false; } }; const removeDuplicateJSON = function removeDuplicateJSON(arr) { var hashTable = {}; return arr.filter(function (el) { var key = (0, _stringify2.default)(el); var match = Boolean(hashTable[key]); return match ? false : hashTable[key] = true; }); }; exports.removeDuplicateJSON = removeDuplicateJSON; exports.isJSON = isJSON; let cloneJSON = function cloneJSON(data) { return mergeJSON({}, data); }; const mergeJSON = function mergeJSON(json1, json2) { let result = null; if (isJSON(json2)) { result = {}; if (isJSON(json1)) { for (let key in json1) { if (isJSON(json1[key]) || Array.isArray(json1[key])) { result[key] = cloneJSON(json1[key]); } else { result[key] = json1[key]; } } } for (let key in json2) { if (isJSON(json2[key]) || Array.isArray(json2[key])) { result[key] = mergeJSON(result[key], json2[key]); } else { result[key] = json2[key]; } } } else if (Array.isArray(json1) && Array.isArray(json2)) { let mergedJson = json1.concat(json2); result = removeDuplicateJSON(mergedJson); } else { result = json2; } return result; }; exports.mergeJSON = mergeJSON;