Javascript:将点分隔的字符串转换为嵌套的对象值 [英] Javascript: Convert dot-delimited strings to nested object value

查看:99
本文介绍了Javascript:将点分隔的字符串转换为嵌套的对象值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆对象属性以点分隔的字符串形式出现,例如availability_meta.supplier.price,我需要为<$分配相应的值c $ c>记录['availability_meta'] ['供应商'] ['价格'] 依此类推。

I have a bunch of object attributes coming in as dot-delimited strings like "availability_meta.supplier.price", and I need to assign a corresponding value to record['availability_meta']['supplier']['price'] and so on.

并非一切都是3深度:很多只有1级深度,很多深度超过3级。

Not everything is 3 levels deep: many are only 1 level deep and many are deeper than 3 levels.

有没有一种很好的方法在Javascript中以编程方式分配这个?例如,我需要:

Is there a good way to assign this programmatically in Javascript? For example, I need:

["foo.bar.baz", 1]  // --> record.foo.bar.baz = 1
["qux.qaz", "abc"]  // --> record.qux.qaz = "abc"
["foshizzle", 200]  // --> record.foshizzle = 200

我想我可以一起破解,但我没有任何好处记住算法所以会很感激的建议。我正在使用lodash,如果它有用,并向其他可以快速完成此工作的库开放。

I imagine I could hack something together, but I don't have any good algorithm in mind so would appreciate suggestions. I'm using lodash if that's helpful, and open to other libraries that may make quick work of this.

编辑这是在后端并且不经常运行,因此没有必要优化大小,速度等。事实上,代码可读性对于未来的开发者来说将是一个加分。

EDIT this is on the backend and run infrequently, so not necessary to optimize for size, speed, etc. In fact code readability would be a plus here for future devs.

编辑2 这与引用的副本不同。也就是说,我需要能够为同一个对象多次执行此分配,并且重复答案将每次只覆盖子键。请重新打开!

EDIT 2 This is NOT the same as the referenced duplicate. Namely, I need to be able to do this assignment multiple times for the same object, and the "duplicate" answer will simply overwrite sub-keys each time. Please reopen!

推荐答案

你在问题​​中提到了lodash,所以我想我应该添加他们的简单对象 set() get()函数。只需执行以下操作:

You mentioned lodash in your question, so I thought I should add their easy object set() and get() functions. Just do something like:

_.set(record, 'availability_meta.supplier.price', 99);

您可以在此处阅读更多相关信息: https://lodash.com/docs#set

You can read more about it here: https://lodash.com/docs#set

这些函数也可以让你做更复杂的事情,比如指定数组索引,等:)

These functions let you do more complex things too, like specify array indexes, etc :)

这篇关于Javascript:将点分隔的字符串转换为嵌套的对象值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆