Skip to content

Instantly share code, notes, and snippets.

@rwheadon
Last active October 11, 2023 03:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rwheadon/7f2b842b3e174c4cb5f7a6f3dea7a6ea to your computer and use it in GitHub Desktop.
Save rwheadon/7f2b842b3e174c4cb5f7a6f3dea7a6ea to your computer and use it in GitHub Desktop.
Dynamic update (in-place) of a JSObject with dynamic path via array.
const testOb = {
slot1: {
cubby1: {
envelope1: {
page1: "Hello World",
page2: "Living large",
},
envelope2: {
page1: "No Escape",
page2: "Supercharger",
},
},
cubby2: {
envelope1: {
page1: "Burger King",
page2: "McDonalds",
},
envelope2: {
page1: "Chili's",
page2: "Olive Garden",
},
},
},
slot2: {
cubby1: {
envelope1: {
page1: "Tomato",
page2: "Potato",
},
envelope2: {
page1: "Cherry",
page2: "Grape",
},
},
cubby2: {
envelope1: {
page1: "Parmesan",
page2: "Swiss",
},
envelope2: {
page1: "Chocolate",
page2: "Vanilla",
},
},
},
}
function updateValue(arrayPath, fieldName, value, overWrite) {
let refOb = testOb;
const fieldPath = [...arrayPath, fieldName];
const len = fieldPath.length;
for (let i=0; i<len-1; i++) {
let elem = fieldPath[i];
if( !refOb[elem] ) refOb[elem] = {}
refOb = refOb[elem];
}
if (typeof(value) === 'number' && typeof(refOb[fieldPath[len-1]]) === 'number' && !overWrite) {
refOb[fieldPath[len-1]] += value;
} else {
refOb[fieldPath[len-1]] = value;
}
}
let itemPath = ["slot2","cubby1","envelope2"];
let fieldName = "page2";
// add an object
let newVal = ["Pineapple","ORANGE"];
console.log(`Before update : ${testOb.slot2.cubby1.envelope2.page2}`);
updateValue(itemPath, fieldName, newVal);
console.log(`After update1 : ${testOb.slot2.cubby1.envelope2.page2}`);
itemPath = [...itemPath];
// add a number
newVal = 10;
updateValue(itemPath, fieldName, newVal);
console.log(`After update2 : ${testOb.slot2.cubby1.envelope2.page2}`);
// increment the number
newVal = 21;
updateValue(itemPath, fieldName, newVal);
console.log(`After update3 : ${testOb.slot2.cubby1.envelope2.page2}`);
// decrement the number
newVal = -4;
updateValue(itemPath, fieldName, newVal);
console.log(`After update4 : ${testOb.slot2.cubby1.envelope2.page2}`);
// add a path that isn't there yet
itemPath = ["slot3","cubby2","envelope1"];
newVal = "Honda";
updateValue(itemPath, fieldName, newVal);
console.log(`After update5 : ${testOb?.slot3?.cubby2?.envelope1?.page2}`);
console.log(JSON.stringify(testOb));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment