实现一个set函数来更新对象中任意路径的值

292 阅读1分钟

```/**set(object, path, value)
    const object = { 'a': [{ 'b': { 'c': 3 } }] };
    set(object, 'a[0].b.c', 4);
    console.log(object.a[0].b.c); // => 4
*/
    const object = {'a': [{ 'b':{ 'c': 3 } }] }
    function set(object, path, value) {
        let path1 = path.replace(/\[/g,'.').replace(/\]/g,'');
        objectStr = "object"
        let val = "value"
        let props = path1.split('.')
        let th = ''
        for (let i = 0; i < props.length; i++) {
          th += "['" + props[i] + "']";
        }
          //判断是对象还是字符串
        let isObj = new Function("return " + objectStr + th);
        let e = new Function();
        if (typeof isObj() == "object") {
            e = new Function(objectStr + th + "=" + value);
        } else if (typeof isObj() !== "object") {
            e = new Function(objectStr + th + '="' + value + '"');
        }
        e();
    }
    set(object, 'a[0].b.c', 4);