如何使用字符串创建空的JSON键(是否嵌套)

How can I create empty JSON keys (nested or not) using a string?

本文关键字:是否 嵌套 JSON 何使用 字符串 创建      更新时间:2023-09-26

我目前在JS中构建了这段代码,但它真的非常难看。

有什么更好的方法吗?

它的工作方式基本上是将app.chhat.test这样的字符串作为键,并将teststr这样的值作为值。

我测试长度,看看"父"密钥是否在那里,否则我们会构建它

function constructJson(jsonKey, jsonValue){
    //REWRITE!!!!!!!!
   let jsonObj = langFile;
   let jsonKeyArr = jsonKey.split('.')
   if (jsonKeyArr.length === 1) {
       if (valToAdd === undefined) {
           if (jsonObj[jsonKey] === undefined) {
               jsonObj[jsonKey] = {}
           }
       } else {
           if (jsonObj[jsonKey] === undefined) {
               jsonObj[jsonKey] = valToAdd
           }
       }
   } else if (jsonKeyArr.length === 2) {
       if (jsonObj[jsonKeyArr[0]] === undefined) {
           jsonObj[jsonKeyArr[0]] = {}
       }
       if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] === undefined) {
           jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] = jsonValue
       }
   } else if (jsonKeyArr.length === 3) {
       if (jsonObj[jsonKeyArr[0]] === undefined) {
           jsonObj[jsonKeyArr[0]] = {}
       }
       if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] === undefined) {
           jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] = {}
       }
       if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]] === undefined) {
           jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]] = jsonValue
       }
   } else if (jsonKeyArr.length === 4) {
       if (jsonObj[jsonKeyArr[0]] === undefined) {
           jsonObj[jsonKeyArr[0]] = {}
       }
       if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] === undefined) {
           jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] = {}
       }
       if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]] === undefined) {
           jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]] = {}
       }
       if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]][jsonKeyArr[3]] === undefined) {
           jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]][jsonKeyArr[3]] = jsonValue
       }
   } else if (jsonKeyArr.length === 5) {
       if (jsonObj[jsonKeyArr[0]] === undefined) {
           jsonObj[jsonKeyArr[0]] = {}
       }
       if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] === undefined) {
           jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] = {}
       }
       if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]] === undefined) {
           jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]] = {}
       }
       if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]][jsonKeyArr[3]] === undefined) {
           jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]][jsonKeyArr[3]] = {}
       }
       if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]][jsonKeyArr[3]][jsonKeyArr[4]] === undefined) {
           jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]][jsonKeyArr[3]][jsonKeyArr[4]] = jsonValue
       }
   } else if (jsonKeyArr.length > 5) {
      return console.log("Length over 5 not supported yet!")
   }
   return jsonObj;
}

谨致问候。

当然,一个简单的循环可以很好地完成这项工作。

function constructJson(jsonKey, jsonValue){
    //REWRITE!!!!!!!!
   langFile = {a:{}, foo:{}};// remove this for your own code
   var jsonObj = langFile;
   var jsonKeyArr = jsonKey.split('.');
   var currentValue = jsonObj;
   for(var i = 0; i < jsonKeyArr.length;i++){
       if(currentValue[jsonKeyArr[i]]===undefined){
          currentValue[jsonKeyArr[i]] = {};
       }
       if(i < jsonKeyArr.length-1){
       currentValue =  currentValue[jsonKeyArr[i]];
       }else{
            currentValue[jsonKeyArr[i]] = jsonValue;
       }
   }
   return jsonObj;
}
alert(JSON.stringify(constructJson("a.b.cd.ef", "toto")));

我只是为每个子级别分配一个临时变量。当我在最后一个时,我会赋值。

是的,可以对从拆分字符串创建的数组使用javascript reduce函数。

function namespaceCreateExceptLast(representationOfElementToCreate, baseNamespace) {
    var tokens;
    if (typeof representationOfElementToCreate !== 'string')
        throw new Error('Expecting string as first parameter');
    if (baseNamespace === undefined)
        baseNamespace = window;
    tokens = representationOfElementToCreate.split('.');
    // Remove the last element (which will contain the value)
    tokens.pop();
    // Use reduce to create part by part your new object
    return tokens.reduce(function (prev, property) {
        if (typeof prev !== 'object') {
            throw Error('One property is already defined but not an object, namespace creation has failed', property);
            return undefined;
        } else {
            if (!prev[property])
                prev[property] = {};
            return prev[property];
        }
    }, baseNamespace);
};

然后你可以有:

function constructJson(jsonKey, jsonValue){
    let jsonObj = langFile;
    var lastItem = namespaceCreateExceptLast(jsonKey, jsonObj);
    var lastKey = jsonKey.substring(jsonKey.lastIndexOf('.') + 1);
    lastItem[lastKey] = jsonValue;
}

我添加了一些注释和异常,以帮助您了解它是如何完成的,但它主要基于reduce函数,您可以很容易地获得帮助(https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/reduce)。