Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an object out of dot notation

This is a reverse question to this question.

Given an object x={a:1,b:2} and a string c.d=3, modify object x to the following:

{
  a:1,
  b:2,
  c:{
    d:3
  }
}

I'm looking for a solution that does not use eval. The use case is as follows:

x being a configuration object, we call: config.set("music.shuffle",true)

Now, music.shuffle must be parsed somehow and added to the internal object x inside the config.set function, so that x looks something like:

x={a:1,b:2,music:{shuffle:true}}
like image 347
Nemo Avatar asked Feb 15 '13 08:02

Nemo


People also ask

What is an example of dot notation?

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.

What is dot notation in Python?

Dot notation indicates that you're accessing data or behaviors for a particular object type. When you use dot notation, you indicate to Python that you want to either run a particular operation on, or to access a particular property of, an object type.

What is a dot notation in Java?

The dot operator, also known as separator or period used to separate a variable or method from a reference variable. Only static variables or methods can be accessed using class name. Code that is outside the object's class must use an object reference or expression, followed by the dot (.)

How do you create an object in JavaScript?

To create an object, use the new keyword with Object() constructor, like this: const person = new Object(); Now, to add properties to this object, we have to do something like this: person.


2 Answers

Off the top of my head I guess you can do something like this:

function addValueToObj(obj, newProp) {
    newProp = newProp.split("=");       // separate the "path" from the "value"

    var path = newProp[0].split("."),     // separate each step in the "path"
        val = newProp.slice(1).join("="); // allow for "=" in "value"

    for (var i = 0, tmp = obj; i < path.length - 1; i++) {
       tmp = tmp[path[i]] = {};     // loop through each part of the path adding to obj
    }
    tmp[path[i]] = val;             // at the end of the chain add the value in
}

var x = {a:1, b:2};
addValueToObj(x, "c.d=3");
// x is now {"a":1,"b":2,"c":{"d":"3"}}
addValueToObj(x, "e.f.g.h=9=9");
// x is now {"a":1,"b":2,"c":{"d":"3"},"e":{"f":{"g":{"h":"9=9"}}}}

Demo: http://jsfiddle.net/E8dMF/1/

like image 92
nnnnnn Avatar answered Oct 02 '22 01:10

nnnnnn


You can do this with lodash.set()

> l=require('lodash')
> x={a:1,b:2};
{ a: 1, b: 2 }
> l.set(x, 'c.d', 3)
{ a: 1, b: 2, c: { d: 3 } }
like image 20
krasnaya Avatar answered Oct 02 '22 00:10

krasnaya