const string = `fizz = 3
buzz.one = item1
buzz.one = item2
buzz.one.two = 123
fizzbuzz.root.a.b.c = 13`;
let result = {};
const splited = string.split("\n");
function insertIntoTree(tree, keyParts, value) {
let current = tree;
for (let i = 0; i < keyParts.length - 1; i++) {
const part = keyParts[i];
if (!current[part]) {
current[part] = {};
}
current = current[part];
}
const lastKey = keyParts[keyParts.length - 1];
if (current.hasOwnProperty(lastKey)) {
if (!Array.isArray(current[lastKey])) {
current[lastKey] = [current[lastKey]];
}
current[lastKey].push(value);
} else {
current[lastKey] = value;
}
}
splited.forEach((line) => {
const [key, value] = line.split("=").map((s) => s.trim());
const parsedValue = isNaN(value) ? value : Number(value);
const keyParts = key.split(".");
insertIntoTree(result, keyParts, parsedValue);
});
console.log(JSON.stringify(result, null, 2));
Y29uc3Qgc3RyaW5nID0gYGZpenogPSAzCmJ1enoub25lID0gaXRlbTEKYnV6ei5vbmUgPSBpdGVtMgpidXp6Lm9uZS50d28gPSAxMjMKZml6emJ1enoucm9vdC5hLmIuYyA9IDEzYDsKCmxldCByZXN1bHQgPSB7fTsKCmNvbnN0IHNwbGl0ZWQgPSBzdHJpbmcuc3BsaXQoIlxuIik7CgpmdW5jdGlvbiBpbnNlcnRJbnRvVHJlZSh0cmVlLCBrZXlQYXJ0cywgdmFsdWUpIHsKICBsZXQgY3VycmVudCA9IHRyZWU7CgogIGZvciAobGV0IGkgPSAwOyBpIDwga2V5UGFydHMubGVuZ3RoIC0gMTsgaSsrKSB7CiAgICBjb25zdCBwYXJ0ID0ga2V5UGFydHNbaV07CgogICAgaWYgKCFjdXJyZW50W3BhcnRdKSB7CiAgICAgIGN1cnJlbnRbcGFydF0gPSB7fTsKICAgIH0KCiAgICBjdXJyZW50ID0gY3VycmVudFtwYXJ0XTsKICB9CgogIGNvbnN0IGxhc3RLZXkgPSBrZXlQYXJ0c1trZXlQYXJ0cy5sZW5ndGggLSAxXTsKCiAgaWYgKGN1cnJlbnQuaGFzT3duUHJvcGVydHkobGFzdEtleSk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