美文网首页
object assign keypath value

object assign keypath value

作者: peerben | 来源:发表于2019-05-31 07:23 被阅读0次

    实现一个函数, 该函数接收一个obj, 一个path, 一个value, 实现obj[path] = value, obj类似json格式

    function assignKeyPath(obj, path, value) {
      const pathList: string[] = path.split('.');
    
      let assign = obj;
      while (pathList.length > 0) {
        const key = pathList.shift();
    
        if (pathList.length === 0) {
          assign[key] = value;
          break;
        }
    
        // assign[key] = assign[key] || {};
        assign = typeof assign[key] === 'object' ? assign[key] : (assign[key] = {});
      }
    
      return obj;
    }
    
    const obj = assignKeyPath({}, 'aa.bb.cc', 'hello');
    const obj1 = assignKeyPath({aa: {dd: 1}}, 'aa.bb.cc', 'hello');
    const obj2 = assignKeyPath({aa: 1}, 'aa.bb.cc', 'hello');
    console.log(`obj ${JSON.stringify(obj)}`);
    console.log(`obj ${JSON.stringify(obj1)}`);
    console.log(`obj ${JSON.stringify(obj2)}`);
    
    Screen Shot 2019-05-31 at 7.23.14 AM.png

    相关文章

      网友评论

          本文标题:object assign keypath value

          本文链接:https://www.haomeiwen.com/subject/soyitctx.html