Exercise 10: Set Nested Property Value
Problem Statement
Function `set(obj, path, value)` banao jo nested object me path string se value set kare.
Example: set({}, "a.b.c", 1) => {a: {b: {c: 1}}}
Sample Output:
set({}, "a.b.c", 1) => {a: {b: {c: 1}}}
set({x: 1}, "y.z", 2) => {x: 1, y: {z: 2}}Solution
const set = (obj, path, value) => {
const keys = String(path).split(".");
const lastKey = keys.pop();
let current = obj;
for (const key of keys) {
if (!(key in current) || typeof current[key] !== "object" || current[key] === null) current[key] = {};
current = current[key];
}
current[lastKey] = value;
return obj;
};Explanation
Overall Goal:
- Nested object me path string se value set karna.
Real world:
- Data manipulation: nested updates.
- Form handling: nested form data.