创建JavaScript对象,从拆分的字符串中。

huangapple go评论77阅读模式
英文:

Create Javascript Object from splitted String

问题

我正在寻找一个能够从以下格式创建对象的“组函数”:

"0_tags.0": {
    "common": {
    },
    "native": {
        "topic": "Stromerfassung_251/Zähler0-Leistung"
    }
},
"0_tags.0.Various": {
    "common": {
    },
    "native": {
        "topic": "Stromerfassung_251/Zähler0-Leistung"
    }
},
"0_tags.0.Various.Stromerfassung_251/Zähler0-Leistung": {
    "common": {
    },
    "native": {
        "topic": "Stromerfassung_251/Zähler0-Leistung"
    }
},
"0_tags.0.Various.Test-String": {
    "common": {
    },
    "native": {
        "topic": "Stromerfassung_251/Zähler0-Leistung"
    }
},
"0_tags.0.Various.battery_charge": {
    "common": {
    },
    "native": {
        "topic": "Stromerfassung_251/Zähler0-Leistung"
    }
}

这应该动态地产生以下结果:

"0_tags": {
    "0": {
        "Various": {
            "Stromerfassung_251/Zähler0-Leistung": {
                "common": {},
                "native": {
                    "topic": "Stromerfassung_252/Zähler0-Leistung"
                }
            },
            "Test-String": {
                "common": {},
                "native": {
                    "topic": "Stromerfassung_253/Zähler0-Leistung"
                }
            },
            "battery_charge": {
                "common": {},
                "native": {
                    "topic": "Stromerfassung_254/Zähler0-Leistung"
                }
            }
        }
    }
}

我的起点如下:

for (d in jsonArray) {
    var item = d.split('.');
    
    if (obj[item[0]] == undefined) {
        obj[item[0]] = {};
    }
    if (obj[item[0]][item[1]] == undefined) {
        obj[item[0]][item[1]] = {};
    }
    
    obj[item[0]][item[1]][item[2]] = jsonArray[d];
}

但这个方法不是动态的,而是在第2级时硬编码了。您是否有任何建议?

提前感谢您!

英文:

i am searching a "group function" for an object, which can be created from the following format:

"0_tags.0": {
    "common": {
    },
    "native": {
        "topic": "Stromerfassung_251/Zähler0-Leistung"
    }
},
"0_tags.0.Various": {
    "common": {
    },
    "native": {
        "topic": "Stromerfassung_251/Zähler0-Leistung"
    }
},
"0_tags.0.Various.Stromerfassung_251/Zähler0-Leistung": {
    "common": {
    },
    "native": {
        "topic": "Stromerfassung_251/Zähler0-Leistung"
    }
},
"0_tags.0.Various.Test-String": {
    "common": {
    },
    "native": {
        "topic": "Stromerfassung_251/Zähler0-Leistung"
    }
},
"0_tags.0.Various.battery_charge": {
    "common": {
    },
    "native": {
        "topic": "Stromerfassung_251/Zähler0-Leistung"
    }
}

Which should dynamically result in:

"0_tags": {
    "0": {
        "Various": {
            "Stromerfassung_251/Zähler0-Leistung": {
                "common": {},
                "native": {
                    "topic": "Stromerfassung_252/Zähler0-Leistung"
                }
            },
            "Test-String": {
                "common": {},
                "native": {
                    "topic": "Stromerfassung_253/Zähler0-Leistung"
                }
            },
            "battery_charge": {
                "common": {},
                "native": {
                    "topic": "Stromerfassung_254/Zähler0-Leistung"
                }
            }
        }
    }
}

My start is as follows:

for (d in jsonArray) {
    var item = d.split('.');

    if (obj[item[0]] == undefined) {
        obj[item[0]] = {};
    }
    if (obj[item[0]][item[1]] == undefined) {
        obj[item[0]][item[1]] = {};
    }

    obj[item[0]][item[1]][item[2]] = jsonArray[d];
}

But this one is not dynamically doing - instead its "hard-coded" till level 2.

Do you perhaps have any suggestions?

Thank you in advance!

答案1

得分: 2

为了动态创建嵌套结构而不硬编码级别,您可以使用递归函数。该函数将处理创建嵌套对象并在每个级别更新适当的属性。

createNestedObject 函数接受父对象 objkeys 数组以及要插入到最深层的 value。它会递归创建嵌套对象,直到到达最后一个键,然后将值分配给它。

使用这种方法,您可以动态处理输入数据中的任何嵌套级别,从而获得所需的输出格式。result 对象将包含按照指定方式转换的数据。

以下是JavaScript中的可能实现:

function createNestedObject(obj, keys, value) {
  let key = keys.shift();

  if (keys.length === 0) {
    obj[key] = value;
  } else {
    if (obj[key] === undefined) {
      obj[key] = {};
    }
    createNestedObject(obj[key], keys, value);
  }
}

const result = {};

for (const key in tagObject) {
  const value = tagObject[key];
  const keys = key.split('.');
  createNestedObject(result, keys, value);
}

console.log(JSON.stringify(result, null, 2));

这段代码实现了动态创建嵌套对象的功能,根据 tagObject 中的数据生成了所需的嵌套结构。

英文:

To dynamically create the nested structure without hard-coding the levels, you can use a recursive function. This function will handle the creation of nested objects and update the appropriate properties at each level.
The createNestedObject function takes the parent object obj, the array of keys, and the value to be inserted at the deepest level. It recursively creates nested objects until the last key is reached, where it assigns the value.

Using this approach, you can handle any level of nesting in the input data dynamically, resulting in the desired output format. The result object will contain the transformed data as specified.

Here's a possible implementation in JavaScript:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

function createNestedObject(obj, keys, value) {
  let key = keys.shift();

  if (keys.length === 0) {
    obj[key] = value;
  } else {
    if (obj[key] === undefined) {
      obj[key] = {};
    }
    createNestedObject(obj[key], keys, value);
  }
}


const result = {};

for (const key in tagObject) {
  const value = tagObject[key];
  const keys = key.split(&#39;.&#39;);
  createNestedObject(result, keys, value);
}

console.log(JSON.stringify(result, null, 2));

<!-- language: lang-html -->

&lt;script&gt;
  const tagObject = {
    &quot;0_tags.0&quot;: {
      &quot;common&quot;: {},
      &quot;native&quot;: {
        &quot;topic&quot;: &quot;Stromerfassung_251/Z&#228;hler0-Leistung&quot;
      }
    },
    &quot;0_tags.0.Various&quot;: {
      &quot;common&quot;: {},
      &quot;native&quot;: {
        &quot;topic&quot;: &quot;Stromerfassung_251/Z&#228;hler0-Leistung&quot;
      }
    },
    &quot;0_tags.0.Various.Stromerfassung_251/Z&#228;hler0-Leistung&quot;: {
      &quot;common&quot;: {},
      &quot;native&quot;: {
        &quot;topic&quot;: &quot;Stromerfassung_251/Z&#228;hler0-Leistung&quot;
      }
    },
    &quot;0_tags.0.Various.Test-String&quot;: {
      &quot;common&quot;: {},
      &quot;native&quot;: {
        &quot;topic&quot;: &quot;Stromerfassung_251/Z&#228;hler0-Leistung&quot;
      }
    },
    &quot;0_tags.0.Various.battery_charge&quot;: {
      &quot;common&quot;: {},
      &quot;native&quot;: {
        &quot;topic&quot;: &quot;Stromerfassung_251/Z&#228;hler0-Leistung&quot;
      }
    }
  };
&lt;/script&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年7月20日 18:21:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76728898.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定