During an interview I've got interesting javascript-task:
Given the code:
const testStr = "bar.baz.foo:111222", testObj = { bar: { baz: { foo: 333444, foo2: 674654 }, boo: { faa: 11 } }, fee: 333 }; function replaceInObj(obj, str) { // your code }
write the implementation of the
replaceInObj
function
- I was not allowed to use 3rd-party library.
- I kinda solved the task, but I'm not satisfied with my solution.
- And I'm struggling with my complex implementation.
- At the same time I cannot find another solution by myself.
My implementation of the replaceInObj
function
const testStr = 'bar.baz.foo:111222';
const testObj = {
bar: {
baz: {
foo: 333444,
foo2: 674654,
},
boo: {
faa: 11,
},
},
fee: 333,
};
console.log('[before] testObj.bar.baz =', testObj.bar.baz);
// run
replaceInObj(testObj, testStr);
console.log('[after] testObj.bar.baz =', testObj.bar.baz);
function replaceInObj(obj, str) {
const [path, valueToChange] = str.split(':');
path.split('.').reduce((acc, prop, index, arr) => {
const isLastProp = arr.length === index + 1;
if (isLastProp) {
acc[prop] = valueToChange;
}
return acc[prop];
}, obj);
}
How would you implement the function replaceInObj
?
- I hope there's much-much simpler implementation.
- And I would be grateful if you'd share your solution