After js simple object is converted to a string, it will be restored to a simple object (such as ^a=$1^b=2 to object)

Description of Requirement

It is now necessary to convert simple objects (property values ​​are only numbers/strings) into the shortest possible string for passing.

Code

let oldObj = {
    
    
  a: 1,
  b: "2",
};

console.log("原对象", oldObj);

let oldObjStr = JSON.stringify(oldObj);

console.log("原对象字符串", oldObjStr, "长度为:", oldObjStr.length);

function obj2str(oldObj) {
    
    
  let newObjStr = "";
  Object.keys(oldObj).forEach((key) => {
    
    
    let value = oldObj[key];
    if (typeof value === "number") {
    
    
      value = "$" + value;
    }
    newObjStr = newObjStr + "^" + key + "=" + value;
  });

  return newObjStr;
}

let newObjStr = obj2str(oldObj);

console.log("新对象字符串", newObjStr, "长度为:", newObjStr.length);

function str2obj(str) {
    
    
  // 按 ^ 分隔字符串
  var key_ValueList = str.split("^");
  var obj = {
    
    };
  var keyValueList;
  key_ValueList.forEach(function (ele, index) {
    
    
    // 按 = 分隔字符串
    keyValueList = key_ValueList[index].split("=");
    if (keyValueList && keyValueList.length === 2 && keyValueList[0]) {
    
    
      var newValue = keyValueList[1];
      // 以 $ 开头的字符串变对象后,数据类型为数字
      if (newValue[0] === "$") {
    
    
        newValue = Number(newValue.substring(1));
      }
      obj[keyValueList[0]] = newValue;
    }
  });
  return obj;
}

let newObj = str2obj(newObjStr);
console.log("恢复后的对象", newObj);

The effect is as follows:

原对象 {
    
     a: 1, b: '2' }
原对象字符串 {
    
    "a":1,"b":"2"} 长度为: 15
新对象字符串 ^a=$1^b=2 长度为: 9
恢复后的对象 {
    
     a: 1, b: '2' }

function encapsulation

Convert a simple object to a string in a specified format

function obj2str(oldObj) {
    
    
  let newObjStr = "";
  Object.keys(oldObj).forEach((key) => {
    
    
    let value = oldObj[key];
    if (typeof value === "number") {
    
    
      value = "$" + value;
    }
    newObjStr = newObjStr + "^" + key + "=" + value;
  });

  return newObjStr;
}

Strings in the specified format are restored as simple objects

function str2obj(str) {
    
    
  // 按 ^ 分隔字符串
  var key_ValueList = str.split("^");
  var obj = {
    
    };
  var keyValueList;
  key_ValueList.forEach(function (ele, index) {
    
    
    // 按 = 分隔字符串
    keyValueList = key_ValueList[index].split("=");
    if (keyValueList && keyValueList.length === 2 && keyValueList[0]) {
    
    
      var newValue = keyValueList[1];
      // 以 $ 开头的字符串变对象后,数据类型为数字
      if (newValue[0] === "$") {
    
    
        newValue = Number(newValue.substring(1));
      }
      obj[keyValueList[0]] = newValue;
    }
  });
  return obj;
}

Guess you like

Origin blog.csdn.net/weixin_41192489/article/details/131592256