0

From a string which looks like:

"Apple Banana 26"

or

"Dog Likes Food"

How would one get objects such as:

Apple={Banana:"26"}

Dog={Likes:"Food"}

David Gamboa
  • 116
  • 1
  • 9

2 Answers2

3

Assuming you want an object not a variables from strings (which gets ugly) you can simply reduceRight()

let str = "Dog Likes Food"

let obj = str.split(' ').reduceRight((obj, word) => ({[word]: obj}))
console.log(obj)

This has the added benefit that it doesn't care how many words you have:

let str = "Dog Likes To Eat Dog Food"

let obj = str.split(' ').reduceRight((obj, word) => ({[word]: obj}))
console.log(obj)

If you are determined to get the variable Dog you can use Object.assign to merge the object with the window object creating a global. But there's almost always a better approach than creating globals:

let str = "Dog Likes Food"

let obj = str.split(' ').reduceRight((obj, word) => ({[word]: obj}))
Object.assign(window, obj)

console.log(Dog)
Mark
  • 90,562
  • 7
  • 108
  • 148
0

You can try to convert the 3-words string to a JSON object, I show you the idea in the next example:

var string1 = "Apple Banana 26";
var string2 = "Dog Likes Food";

// Convert 3 words string to a JSON object.

function strToObj(str)
{
   var items = str.split(' ');
   
   if (items.length != 3)
       return false;

   var jsonStr = '{"' + items[0] + '":' +
                 '{"' + items[1] + '":"' +
                 items[2] + '"}}';

   return JSON.parse(jsonStr);
}

// Test the method.

var apple = strToObj(string1);

if (apple)
    console.log(apple);
else
   console.log("Fail to convert!");
   
var dog = strToObj(string2);

if (dog)
    console.log(dog);
else
   console.log("Fail to convert!");
Shidersz
  • 16,846
  • 2
  • 23
  • 48