Skip to content

Instantly share code, notes, and snippets.

@mikebucks
Last active December 28, 2015 11:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikebucks/7496187 to your computer and use it in GitHub Desktop.
Save mikebucks/7496187 to your computer and use it in GitHub Desktop.
Converts comma separated key/value pairs to a js object.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Name Counts</title>
</head>
<body>
<p>This solution to the keys problem converts the contents of a textarea into an array by line break, then passes that array to a "convertCommaKeysToObject" method which is where the bulk of the oeration takes place. This method iterates through an array of strings which it expects to contain a single comma. It splits each string at the comma, adding the value left of the comma as a new key and the value right of the comma as a value. If a key already exists in the new object it's value is added to the existing key. It then prints the results to the DOM. It uses no 3rd party libs and (almost) passes JSLint.</p>
<hr>
<form>
<textarea id="keys" cols="30" rows="10">
John,2
Jane,3
John,4
Jane,5
</textarea>
<br>
<button id="submit">Tally the vallies</button>
</form>
<div id="results"></div>
<script>
(function () {
'use strict';
var appendResults, convertCommaKeysToObject;
convertCommaKeysToObject = function (data) {
var i, key, obj = {};
if (data === null || data === 'undefined') {
return 'Not enough data >_<';
} else {
for (i = 0; i < data.length; i++) {
key = data[i].split(',');
if (obj.hasOwnProperty(key[0])) {
obj[key[0]] = parseInt(key[1], 0) + parseInt(obj[key[0]], 0);
} else {
obj[key[0]] = parseInt(key[1], 0);
}
}
return obj;
}
};
appendResults = function (data) {
var key, results = [];
if (typeof data === 'object') {
for (key in data) {
if (data.hasOwnProperty(key)) {
results.push('The total for ' + key + ' is ' + data[key] + '. ');
}
}
} else {
results = data;
}
document.getElementById('results').innerHTML = results.join('');
};
document.getElementById('submit').addEventListener('click', function (e) {
var data = document.getElementById('keys')
.value
.replace(/ /g, '')
.match(/[^\r\n]+/g),
names = convertCommaKeysToObject(data);
appendResults(names);
e.preventDefault();
});
}());
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment