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"}

0

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

Comments

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!");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.