Low-code export front-end code encounters some strings and data processing records

overview

Recently, I am doing pure front-end low-code export code function, and some string and data object processing methods encountered are summarized and recorded

1. Delete the double quotes of all keys in the object-to-string conversion

 //str:JSON.stringify后的字符串
   function rmKeyDouquoMarks(str) {
    
    
      return str.replace(
        /("(\\[^]|[^\\"])*"(?!\s*:))|"((\\[^]|[^\\"])*)"(?=\s*:)/g,
        "$1$3"
      );
    }

2. Delete the double quotes of the value corresponding to a certain key in the object-to-string conversion

删除第一个

   //key:值对应的key,str:JSON.stringify后的字符串
   function rmValueDouquoMarks(str, key ) {
    
    
      if (str.split(`${
     
     key}:"`).length > 1) {
    
    
        let newStr = '"' + str.split(`${
     
     key}:"`)[1];
        let target = newStr.substring(0, newStr.indexOf('"', 1) + 1);
        str =
          target.length > 2
            ? str.replace(target, target.substring(1, target.length - 1))
            : str;
      }
      return str;
    }

删除所有

//key:值对应的key,str:JSON.stringify后的字符串
function rmAllValDouquoMarks(str,key){
    
    
    while (str.includes( `${
     
     key}:"`)) {
    
    
        str = rmValueDouquoMarks(str, key);
      }
      return str;
}

3. String conversion function

//str:字符串,that需要绑定的this
function strChangeToFun(str, that = null) {
    
    
  let fn = null;
  if (str && typeof str === "string") {
    
    
    try {
    
    
     let  func = new Function("return " + str);
      that && (func = func.bind(that))
      if (typeof func() === "function") {
    
    
        fn=func()
      }
    } catch (e) {
    
     }
  }
  return fn;
}

4. Two object data mixing

解释:目标对象合并源对象生成新对象,目标对象优先级高于源对象,如果目标对象有值将取目标对象值否者取源对象值,数组类型强制覆盖或者子元素去重合并可选。有点类似vue mixins功能

/**
 * 
 * @param {
    
    *} obj 源对象
 * @param {
    
    *} target 目标对象
 * @param {
    
    *} arrAssginType 数组合并类型 0:强行target替换obj,1:子元素合并一起
 * @returns 
 */
const assginObject = function (obj, target, arrAssginType = 0) {
    
    
  const allKeys = function (obj, target) {
    
    
    let targetKeys = Object.keys(target);
    Object.keys(obj).forEach((key) => {
      if (!targetKeys.includes(key)) targetKeys.push(key);
    });
    return targetKeys;
  };

  const isNullOrUndefined = function (val) {
    
    
    return val === null || val === undefined;
  };

  if (Object.prototype.toString.call(obj) === "[object Object]") {
    
    
    let allKeysArr = allKeys(obj, target);
    let newObj = {
    
    };
    for (let key of allKeysArr) {
    
    
      if (Object.prototype.toString.call(obj[key]) === "[object Object]") {
    
    
        newObj[key] = assginObject(
          obj[key],
          (target && target[key]) || {
    
    }
        );
      } else if (obj[key] && Array.isArray(obj[key])) {
    
    
        newObj[key] = assginObject(
          obj[key],
          (target && target[key]) || []
        );
      } else {
    
    
        newObj[key] = !isNullOrUndefined(target[key]) ? target[key] : obj[key]

      }
    }
    return newObj;
  } else if (obj && Array.isArray(obj)) {
    
    
    return arrAssginType ?  [...new Set([...obj, ...target])]:[...target]
  } else {
    
    
    return isNullOrUndefined(target) ? obj : target;
  }
}

export default assginObject

5. Data object deep copy


//对象深度克隆
const deepClone = obj => {
    
    
    function isNullOrUndefined(val) {
    
    
        return val === null || val === undefined
    }
    if (Array.isArray(obj)) {
    
     //数组类型
        return obj.map(item => {
    
    
            return isNullOrUndefined(item) ? item : deepClone(item)//null和undefined无原型直接返回
        })

    } else if (Object.prototype.toString.call(obj) === '[object Object]') {
    
    //对象类型
        let newObj = {
    
    }
        for (let key in obj) {
    
    
            if (obj.hasOwnProperty(key)) {
    
    
                newObj[key] = isNullOrUndefined(obj[key]) ? obj[key] : deepClone(obj[key])
            }
        }
        return newObj

    }
    return obj.valueOf()//其他类型(基本类型或函数)
}
export default deepClone


6. String content export code file

   //字符串导出代码文件,content:字符串内容,filename文件名
   function exportLowCode(content, filename) {
    
    
      let elLink = document.createElement("a");
      elLink.download = filename;
      elLink.style.display = "none";
      let blob = new Blob([content]);
      elLink.href = URL.createObjectURL(blob);
      document.body.appendChild(elLink);
      elLink.click();
      document.body.removeChild(elLink);
    }

Supongo que te gusta

Origin blog.csdn.net/sd1sd2/article/details/131258675
Recomendado
Clasificación