JSFiddle - React, Tailwind, and code Playground
by neonDog
HTML
<script src="https://cdn.jsdelivr.net/npm/deep-diff@1/dist/deep-diff.min.js"></script>
JavaScript
const delChildren = function(obj, addedIds=[]) {
for (const key in obj) {
if (addedIds.includes(key)) {
delete obj[key];
}
}
};
const flattenObj = function(obj, ids=[]) {
const addedIds = [];
const flatten = function(obj, res={}) {
for (const key in obj) {
const item = obj[key];
if (ids.includes(key)) {
res[key] = item;
if ('children' in item && typeof item.children === 'object') {
Object.assign(res, flatten(item.children, res) );
}
if ('children' in item) {
delChildren(res[key].children, addedIds);
if (Object.keys(res[key].children).length === 0) {
delete res[key].children;
}
}
if (Object.keys(res[key]).length === 0) {
delete res[key];
}
addedIds.push(key);
}
}
return res;
};
return flatten(obj);
};
const getIds = function(obj) {
const arr = [];
for (const key in obj) {
arr.push(key);
if (obj[key] && 'children' in obj[key] && typeof obj[key].children === 'object'){
arr.push(...getIds(obj[key].children));
}
}
return arr;
};
const unFlattenObj = function(obj, flatObj) {
for (const key in obj) {
if (key in flatObj) {
Object.assign(obj[key], flatObj[key]);
}
if ('children' in obj[key] && typeof obj[key].children === 'object') {
unFlattenObj(obj[key].children, flatObj);
}
}
return obj;
};
function deepDiff (obj1, obj2, keepNewKeys = false) {
if (typeof obj1 !== 'object') {
throw new TypeError('First parameter must be an object')
}
if (typeof obj2 !== 'object') {
throw new TypeError('Second parameter must be an object')
}
const diff = {}
Object.keys(obj2).forEach((key) => {
if (!obj1.hasOwnProperty(key)) {
...