var list = { 'friends': { 'fred': '123-4567', 'lisa': '123-6789' }, 'work': { 'joe': '234-5678' } }; /* original function */ function old_addName(group, name, number) { if (list[group] && list[group][name]) { list[group][name] = number; } else { if (list[group]) { list[group][name] = number; } else { list[group] = {}; list[group][name] = number; } } } /* more efficient function */ function addName(group, name, number) { if (!list[group]) { list[group] = {}; } list[group][name] = number; } /**************** * Demo stuff ****************/ function showContacts(){ var t = ''; $.each(list, function(g){ t += '\n' + g.toUpperCase() + '\n=======\n'; $.each(list[g], function(n){ t += n + ' : ' + list[g][n] + '\n'; }); }); $('textarea').val(t); } $('button').click(function(){ var i = $('input'), t = ($(this).attr('data-test') || ',,').split(','), g = i.eq(0).val() || t[0], n = i.eq(1).val() || t[1], b = i.eq(2).val() || t[2]; if (g && n && b) { addName(g.toLowerCase(), n, b); showContacts(); } i.val(''); }); showContacts();
Group: <input type="text" placeholder="Enter a group"><br> Name : <input type="text" placeholder="Enter a name"><br> Number: <input type="text" placeholder="Enter the number"><br> <button>Add</button> <button data-test="emergency,Police,911">Add Police</button><br> <br>Contacts<br> <textarea readonly rows="20" cols="30"></textarea>