JSFiddle - React, Tailwind, and code Playground
by neonDog
JavaScript
const isNumeric = function (n) {
return !isNaN(parseFloat(n)) && isFinite(n);
};
const addToObj = (obj, path, value) => { //https://stackoverflow.com/questions/54733539/javascript-implementation-of-lodash-set-method
const pList = Array.isArray(path) ? path : path.split('.');
const len = pList.length;
// changes second last key to {}
for (let i=0; i < len - 1; i++) {
const elem = pList[i];
if (!obj[elem] || typeof obj[elem] !== 'object') {
//If the next path is an array index lets create an array
if (i + 1 < len && (pList[i+1] === '*' || isNumeric(pList[i+1]))) {
pList[i+1] = 0;
obj[elem] = [];
} else {
//Otherwise create an object
obj[elem] = {};
}
}
obj = obj[elem];
}
if (Array.isArray(obj)) {
if (pList[len - 1] === '*') {
obj.push(value);
} else if (isNumeric(pList[len - 1])) {
obj[parseInt(pList[len - 1])] = value;
} else {
obj.unshift(value);
}
} else {
// set value to second last key
obj[pList[len - 1]] = value;
}
};
const obj = {};//id:1, address: {city: 'Minsk', street: 'Prityckogo 12'}}
//setByString(obj, 'address.city', 'Grodno'); //obj.address.city => 'Grodno'
//setByString(obj, ['address', 'city'], 'Grodno'); //obj.address.city => 'Grodno'
addToObj(obj, ['address', 'city', 'home'], 'Grodno'); //obj.address.city => 'Grodno'
addToObj(obj, ['address', 'city', '*', 'bitch'], 'Grodno');
addToObj(obj, ['address', 'city', '*'], 'Poo');
addToObj(obj, ['id'], 2);
addToObj(obj, ['variations','*'], {});
addToObj(obj, ['variations','*'], {});
addToObj(obj, ['variations','*'], {});
console.log(JSON.stringify(obj));