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.
JavaScript
x
8
1
{
2
Apple: "fruit",
3
Banana: "fruit",
4
Kiwi: "fruit",
5
Orange: "fruit",
6
Tomato: "vegetable"
7
}
8
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.
JavaScript
1
19
19
1
function myFormatter(input) {
2
var result = {};
3
4
input.split('. ').forEach(function(bit) {
5
var a = bit.split(': ');
6
var keys = a[0];
7
var value = a[1];
8
9
keys.split(' ').forEach(function(thisKey) {
10
result[thisKey] = value;
11
});
12
});
13
14
return result;
15
}
16
17
console.log(myFormatter('Apple Banana Kiwi Orange: fruit. Tomato: vegetable'));
18
19
console.log(myFormatter('Tomato: maybe a fruit. Apple Banana Orange: fruit. Carrots: vegetable'));