Assigning nested values ​​to (partially) undefined objects

Let's say I want to assign a value similar to this:

x.label1.label2.label3 = someValue;
// or equivalently:
x['label1']['label2']['label3'] = someValue;

This works as long as it x.label1.label2is determined, but otherwise a reference error will be used. This, of course, makes sense. But is there an easy way to assign this anyway where it just creates the necessary nested objects?

So for example, if xequal { label1: {}, otherLabel: 'otherValue' }, I want to update xto become{ label1: { label2: { label3: someValue } }, otherLabel: otherValue }

I think I could write a function myself, but is there a language function or a standard library function that does this?

+4
source share
5 answers
+1

Proxy. get, - . "" . :

let traps = {
    get: function (target, name) {
        if (!(name in target))
            target[name] = new Proxy({}, traps);

        return target[name];
    }
};

let x = new Proxy({}, traps);

x , , :

x.label1.label2.label3 = 'foo';

. , , . , in, , .

+1

, , :

function assignByPath(obj, path, value) {
  var field = path.split('>'),
      last = field.pop();

  field.reduce(
    function(node, f) {
      return node[f] = node[f] instanceof Object ? node[f] : {};
    }, obj
  )[last] = value;
}

var myObj = {};
assignByPath(myObj, 'label1>label2>label3', 'someValue');

console.log(myObj);

Object.prototype, :

myObj.assignByPath('label1>label2>label3', 'someValue');

.

+1

Array.prototype.shift(), Object.assign(),

var x = {
  label1: {},
  otherLabel: "otherValue"
};

var nestprops = (props, value, obj, o, curr = props.shift()) => props.length 
  ? nestprops(props, value, (Object.assign(obj, {[curr]: {}}) && obj[curr]), o) 
  : ((!value || value) && (obj[curr] = value) && o);

console.log(nestprops(["label1", "label2", "label3"], "someValue", x, x));
+1

Check the length of the keys inside label1 objectif it is equal 0, then change it to the desired object .

Here is a snippet , hope this helps.

var obj = { label1: {}, otherLabel: 'otherValue' };

if(Object.keys(obj.label1).length == 0 ) {
    obj.label1 = { label2: { label3: "value3" } };
}
console.log(obj);
Run code
0
source

Source: https://habr.com/ru/post/1650471/


All Articles