JSFiddle - React, Tailwind, and code Playground
by neonDog
JavaScript
//From lodash
const getObj = function (object, path) {
//If path is a json schema path, convert it to array
if (typeof path === 'string' && path.length > 0 && path[0] === '#') {
path = path.split('/');
path.shift();
}
let index = 0;
const length = path.length;
if (length === 0) {
return object;
}
while (object != null && index < length) {
object = object[path[index++]];
}
return (index && index == length) ? object : undefined;
};
const createDeepPath = function(path) {
const p = [];
for (let i=0,l=path.length; i < l; i++) {
p.push('children',path[i]);
}
return p;
};
//Source: https://gomakethings.com/how-to-add-a-new-item-to-an-object-at-a-specific-position-with-vanilla-js/
const addToObject = function (obj, key, value, searchKey=null, append=true, index=null) {
// Create a temp object and index variable
const temp = {};
let i = 0,
added = false;
// Loop through the original object
for (const prop in obj) {
if (obj.hasOwnProperty(prop)) {
// Add the current item in the loop to the temp obj
if (append && prop !== key) {
temp[prop] = obj[prop];
}
if (key && (searchKey && searchKey === prop) || (index !== null && i === index)) {
temp[key] = value;
added = true;
}
// Add the current item in the loop to the temp obj
if (!append && prop !== key) {
temp[prop] = obj[prop];
}
i++;
}
}
// If it wasn't added anywhere, add it to the end
if (!added) {
temp[key] = value;
}
return temp;
};
const NeonCRUD = {
add: (targetObj, path=[], newObj={}) => {
let obj = getObj(targetObj, path);
if (obj && Array.isArray(obj)) {
obj.push(newObj);
return true;
}
const last = Array.isArray(path) ? path.pop() : path;
obj = getObj(targetObj, path);
if (!obj) {
return false;
} else if (Array.isArray(obj)) {
obj.push(newObj)
} else {
obj[last] = newObj;
}
return true;
},
remove:...