Sobes.tech
Middle

Practical task: given a string of the form 'value.value.value', it is necessary to convert it into a nested object where each key is a part of the string, and the last key contains an empty object.

sobes.tech AI

Answer from AI

To convert a string like 'value.value.value' into a nested object, where each key is a part of the string and the last key contains an empty object, you can use the following approach in JavaScript:

function stringToNestedObject(str) {
  const parts = str.split('.');
  const result = {};
  let current = result;

  for (let i = 0; i < parts.length; i++) {
    current[parts[i]] = (i === parts.length - 1) ? {} : {};
    current = current[parts[i]];
  }

  return result;
}

// Example usage:
const input = 'value.value.value';
const output = stringToNestedObject(input);
console.log(JSON.stringify(output, null, 2));

The result will be:

{
  "value": {
    "value": {
      "value": {}
    }
  }
}

Thus, the function splits the string by dots and sequentially creates nested objects.