Skip to content
Advertisement

format well defined string to an object using es5

I have either of these string:

var str = "Apple Banana Kiwi Orange: fruit. Tomato: vegetable"

or

var str = "Tomato: maybe a fruit. Apple Banana Orange: fruit. Carrots: vegetable".

I want to format it to an object of this format only using ES5.

{
Apple: "fruit",
Banana: "fruit",
Kiwi: "fruit",
Orange: "fruit",
Tomato: "vegetable"
}

I tried a combination of using split() and nested for loop, but I’m not sure it’s the best solution.

Advertisement

Answer

I had some time and quickly wrote something and relies heavily on whitespace. You may want to make sure you clean your input on each step but I leave that up to you.

function myFormatter(input) {
  var result = {};
  
  input.split('. ').forEach(function(bit) {
    var a = bit.split(': ');
    var keys = a[0];
    var value = a[1];
    
    keys.split(' ').forEach(function(thisKey) {
      result[thisKey] = value;
    });
  });
  
  return result;
}

console.log(myFormatter('Apple Banana Kiwi Orange: fruit. Tomato: vegetable'));

console.log(myFormatter('Tomato: maybe a fruit. Apple Banana Orange: fruit. Carrots: vegetable'));
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement