I'm trying to build a function that would expand an object like :
{ 'ab.cd.e' : 'foo', 'ab.cd.f' : 'bar', 'ab.g' : 'foo2' }
Into a nested object :
{ab: {cd: {e:'foo', f:'bar'}, g:'foo2'}}
Like this php function : Set::expand()
Without using eval of course.
You can create nested objects within a nested object. In the following example, Salary is an object that resides inside the main object named Employee . The dot notation can access the property of nested objects.
Use the JavaScript function JSON. parse() to convert text into a JavaScript object: const obj = JSON. parse('{"name":"John", "age":30, "city":"New York"}');
Dot notation is one way to access a property of an object. To use dot notation, write the name of the object, followed by a dot (.), followed by the name of the property. Example: var cat = { name: 'Moo', age: 5, }; console.
This means dot notation is not an option when using a variable to represent the object's key we are trying to access because to use dot notation, we must be able to type out the exact letter-by-letter name the key. Bracket notation gives us the ability to use variables to access values in an object.
I believe this is what you're after:
function deepen(obj) { const result = {}; // For each object path (property key) in the object for (const objectPath in obj) { // Split path into component parts const parts = objectPath.split('.'); // Create sub-objects along path as needed let target = result; while (parts.length > 1) { const part = parts.shift(); target = target[part] = target[part] || {}; } // Set value at end of path target[parts[0]] = obj[objectPath] } return result; } // For example ... console.log(deepen({ 'ab.cd.e': 'foo', 'ab.cd.f': 'bar', 'ab.g': 'foo2' }));
If you're using Node.js (e.g. - if not cut and paste out of our module), try this package: https://www.npmjs.org/package/dataobject-parser
Built a module that does the forward/reverse operations:
https://github.com/Gigzolo/dataobject-parser
It's designed as a self managed object right now. Used by instantiating an instance of DataObjectParser.
var structured = DataObjectParser.transpose({ 'ab.cd.e' : 'foo', 'ab.cd.f' : 'bar', 'ab.g' : 'foo2' });
structured.data()
returns your nested object:
{ab: {cd: {e:'foo', f:'bar'}, g:'foo2'}}
So here's a working example in JSFiddle:
http://jsfiddle.net/H8Cqx/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With