javascriptarraysobjectlodash

Convert dot-delimited strings to nested object value


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.

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

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

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.

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.

I need to be able to do this assignment multiple times for the same object.


Solution

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

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