Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add property chain to JS Object

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)?

like image 393
weidler Avatar asked Mar 13 '23 04:03

weidler


2 Answers

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);
like image 131
Matt Burland Avatar answered Mar 19 '23 18:03

Matt Burland


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.

like image 30
StriplingWarrior Avatar answered Mar 19 '23 19:03

StriplingWarrior