Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic deep selection for a JavaScript object

With a single property this is fairly easy:


var jsonobj = {
    "test": "ok"
}
var propname = "test";
// Will alert "ok"
alert(jsonobj[propname]);

But what I want to do is use a nested property:


var jsonobj = {
    "test": {
        "test2": "ok"
    }
}
var propname = "test.test2";
// Alerts undefined
alert(jsonobj[propname]);

Is there any way of selecting a nested "dynamic" property? I know I can do jsonobj.test.test2, but the problem is that propname can change to a property that goes 1,2 or 3 levels deep. (e.g test, test.test2, ...)

like image 460
user403428 Avatar asked Jul 27 '10 14:07

user403428


People also ask

How do I create a dynamic object key?

To create an object with dynamic keys in JavaScript, you can use ES6's computed property names feature. The computed property names feature allows us to assign an expression as the property name to an object within object literal notation.

How do we add remove properties to objects dynamically in JS?

Adding/Removing Properties from an Object: For adding any property, one could either use object_name. property_name = value (or) object_name[“property_name”] = value. For deleting any property, one could easily use delete object_name. property_name (or) delete object_name[“property_name”].

Can you nest objects in JavaScript?

JavaScript can store data through key-value pairs. The key-value pairs are associated with the JavaScript objects. Objects contain properties that can be stored in nested objects. These nested objects are created within other objects and accessed through dot or bracket notation.


1 Answers

I also just implemented this using an inner recursive function like so:

function get(obj, ns) {            

    function recurse(o, props) {
        if (props.length === 0) {
            return o;
        }
        if (!o) {
            return undefined;
        }
        return recurse(o[props.shift()], props);
    }

    return recurse(obj, ns.split('.'));
}

This will return the deep value of the property specified by the ns param, otherwise will always return undefined if it doesn't exist or there are any problems along the way.

like image 173
sym3tri Avatar answered Oct 18 '22 15:10

sym3tri