简体   繁体   English

如何替换 Lodash 的 get 和 set 以在高度复杂的对象中获取和设置属性

[英]How to replace Lodash's get and set to get and set properties in highly complex objects

I am using lodash 's get and set to manipulate complex objects.我正在使用lodashgetset来操作复杂的对象。 Although Lodash is a good library, it also weighs considerably (about 40kb).尽管 Lodash 是一个很好的库,但它的重量也很大(大约 40kb)。 I am tring to develop a lean web-app, and lodash takes half of the bundle size.我正在尝试开发一个精简的网络应用程序,而 lodash 占用了包大小的一半。

How would you build safe functions that can replace get and set ?您将如何构建可以替代getset的安全函数?

For instance, some function which will change the following object:例如,某些 function 将更改以下 object:

Set

const a = {b:2,c:{d:5}}

set(a,"cd",7)

Which will result这将导致

//a = {b:2,c:{d:7}} . //a = {b:2,c:{d:7}} .

if a = {}, it will result:如果 a = {},它将导致:

{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 //x = 5或者如果路径不存在, //x = 0

You can build a recursive function in JavaScript to do that.您可以在 JavaScript 中构建递归 function 来做到这一点。

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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM