Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a way to automatically create a javascript object by just assigning a property?

I am doing a project which requires to pass Perl objects to javascript via JSON. I am facing a problem in terms of "intermediate" object definition.

In Perl, object is represented by hash, and programmers don't have to define anything "in the middle". Once a property is created, all intermediate objects are automatically created as hash references. e.g.

$graph{chart}{yAxis}{title} = "Temperature Tracking";

However, once this object is passed to Javascript, if I want to add any new properties in the "intermediate" object, like:

graph.chart.xAxis.title = "Time Sequence";

I'll have an "undefined graph.chart.xAxis" error. Unlike Perl, Javascript doesn't automatically create objects if we simply assign a property for it.

At the moment I have to use below solution:

if (!graph.chart.xAxis) {
  graph.chart.xAxis = {};
  graph.chart.xAxis.title = "Time Sequence";
}

Unfortunately, in our project the objects passed from Perl are pretty dynamic and there are plenty of other objects that Javascript may not know. Above way makes JS code pretty lengthy and "ugly looking". Are there any better solutions to make Javascript behave like Perl, which means I don't have to create intermediate objects manually?

like image 342
BebbaPig Avatar asked Jan 14 '23 22:01

BebbaPig


2 Answers

I'm not sure whether this meets your requirements but a simple function to create the missing objects could look like this:

function insertNode(obj, node, value) {
    var segments = node.split('.');
    var key = segments.pop();
    var ref = obj;

    while (segments.length > 0) {
        var segment = segments.shift();
        if (typeof ref[segment] != 'object') {
            ref[segment] = {};
        }
        ref = ref[segment];
    }

    ref[key] = value;
};

var x = {};
insertNode(x, 'foo.bar.baz', 'hello world');
alert(x.foo.bar.baz); // "hello world"

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

like image 111
Niko Avatar answered Jan 19 '23 10:01

Niko


You may be interested in a library called steeltoe

steelToe(graph).set('chart.xAxis.title', 'Time Sequence');
like image 27
Prinzhorn Avatar answered Jan 19 '23 10:01

Prinzhorn