When you are dealing with data where the contents may vary and you don't want to necessarily run into Uncaught TypeError: Cannot read properties of undefined
When the path is generated at runtime. lodash supports this functionality with result and get. obj.a.b.c can only be specified at design time - i.e. when you write the code. Dealing with "self-describing data" it is sometimes necessary to formulate a path programmatically at runtime and then access (and/or mutate) it.
consttext='{"a":{"b":{"c":12,"j":false},"k":null}, "target":"a.b.c"}';constdata=JSON.parse(text);constother={a:{...JSON.parse(text).a,d:{c:0}},target:'a.d.c'};increment(data);// i.e. increment at a.b.cincrement(other);// i.e. increment at a.d.c// ... just checkingconsole.log(data.a.b.c);// 13console.log(other.a.d.c);// 1functionincrement(data){constpath=data.target;constvalue=_.get(data,path);_.set(data,path,typeofvalue==='number'?value+1:0);}
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I don't understand why you need that.
a simple:
gives the same result.
Yes, but I guess it is more like a challenge.
When you are dealing with data where the contents may vary and you don't want to necessarily run into
Uncaught TypeError: Cannot read properties of undefined
If the path is fixed at design time in modern JavaScript you can use the Optional chaining (?.) and Nullish coalescing operator (??) operator to avoid errors.
When the
path
is generated at runtime. lodash supports this functionality with result and get.obj.a.b.c
can only be specified at design time - i.e. when you write the code. Dealing with "self-describing data" it is sometimes necessary to formulate apath
programmatically at runtime and then access (and/or mutate) it.