I am using lodash
's get
and set
to manipulate complex objects. Although Lodash is a good library, it also weighs considerably (about 40kb). I am tring to develop a lean web-app, and lodash takes half of the bundle size.
How would you build safe functions that can replace get
and set
?
For instance, some function which will change the following object:
Set
const a = {b:2,c:{d:5}}
set(a,"cd",7)
Which will result
//a = {b:2,c:{d:7}}
.
if a = {}, it will result:
{c:{d:7}}
Get
const a = {b:2,c:{d:5}}
let x = get(a,"cd",0)
Which will result
//x = 5
or if the path doesn't exist, //x = 0
You can build a recursive function in JavaScript to do that.
To set the data:
const obj = {b:7,c:{d:{f:8}}}; const set = (string, obj, value) => { const [current,...rest] = string.split("."); rest.length >= 1? set(rest.join("."), obj[current] = obj[current] || {}, value): obj[current]= value; return obj; }; console.log(set("cdf", obj, 10));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.