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, ...)
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.
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”].
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.
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.
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