Accessing or creating nested JavaScript objects with string key without eval

前端 未结 2 1409
无人及你
无人及你 2020-12-04 00:35

I am looking for a nice solution to access a property by string value, but if the property does not exist it should create it. If the root structure already has defined some

相关标签:
2条回答
  • 2020-12-04 01:01

    You could split the path and reduce the path by walking the given object. If no Object exist, create a new property with the name, or an array. Later assign the value.

    function setValue(object, path, value) {
        var way = path.replace(/\[/g, '.').replace(/\]/g, '').split('.'),
            last = way.pop();
    
        way.reduce(function (o, k, i, kk) {
            return o[k] = o[k] || (isFinite(i + 1 in kk ? kk[i + 1] : last) ? [] : {});
        }, object)[last] = value;
    }
    
    var test = {};
    setValue(test, "foo.name", "Mr. Foo");
    setValue(test, "foo.data[0].bar", 100);
    setValue(test, "and.another[2].deep", 20);
    console.log(test);

    0 讨论(0)
  • 2020-12-04 01:22

    I wouldn't reinvent the wheel in this case, and instead use lodash. Specifically the set() function. As per their example:

    var object = { 'a': [{ 'b': { 'c': 3 } }] };
    
    _.set(object, 'a[0].b.c', 4);
    console.log(object.a[0].b.c);
    // => 4
    
    _.set(object, ['x', '0', 'y', 'z'], 5);
    console.log(object.x[0].y.z);
    // => 5
    
    0 讨论(0)
提交回复
热议问题