Is it possible in one line to add a property to an added property of an added property of ...
var some_object = {};
some_object.prop_a = "hi";
some_object.prop_b.prop_c.prop_d = "ho";
while line 2 obviously works, line 3 doesnt as it returns the cannot read property of undefined
error. I know, that prop_b and prop_c dont exist when prop_d should be assigned. But is there a simple one-liner to do what i want to do (i.e. add a nested property even if some levels in the nested object dont exist yet)?
You could certainly write a function to do this. Something like this perhaps:
function addPropertyChain(chain, val, obj) {
var propChain = chain.split(".");
if (propChain.length === 1) {
obj[propChain[0]] = val;
return;
}
var first = propChain.shift();
if (!obj[first]) {
obj[first] = {};
}
addPropertyChain(propChain.join("."), val, obj[first] );
}
var some_object = {};
addPropertyChain("prop_b.prop_c.prop_d","ho",some_object);
console.log(some_object);
I know, that prop_b and prop_c dont exist when prop_d should be assigned.
If this is the case, you can do this:
some_object.prop_b = {
prop_c : {
prop_d : "ho"
}
};
(Or, in one line:)
some_object.prop_b = { prop_c : { prop_d : "ho" } };
You're just using JavaScript's object initializer syntax to create nested objects.
However, beware as this would overwrite any existing prop_b
or prop_b.prop_c
values, if those values already existed.
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