Javascript:将点分隔的字符串转换为嵌套的对象值 [英] Javascript: Convert dot-delimited strings to nested object value
问题描述
我有一堆以点分隔的字符串形式出现的对象属性,例如 "availability_meta.supplier.price"
,我需要为 record['availability_meta' 分配一个相应的值]['supplier']['price']
等等.
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.
EDIT 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屋!