Posts

Showing posts with the label Associative Array

Creating An Associative Array In JavaScript Using The Map Function

Answer : You may use Array.prototype.reduce for your task. It allows a return value in the callback function for the next call. var data = [ { 'list': 'one', 'item': 1 }, { 'list': 'one', 'item': 2 }, { 'list': 'one', 'item': 3 }, { 'list': 'two', 'item': 1 }, { 'list': 'two', 'item': 2 } ], flat = data.reduce(function (r, a) { r[a.list] = r[a.list] || []; r[a.list].push(a.item); return r; }, {}); document.write('<pre>' + JSON.stringify(flat, 0, 4) + '</pre>');

Copy An Associative Array In JavaScript

Answer : In JavaScript, associative arrays are called objects. <script> var some_db = { "One" : "1", "Two" : "2", "Three" : "3" }; var copy_db = clone(some_db); alert(some_db["One"]); alert(copy_db["One"]); function clone(obj) { if (null == obj || "object" != typeof obj) return obj; var copy = obj.constructor(); for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]); } return copy; } </script> I would normally use var copy_db = $.extend({}, some_db); if I was using jQuery. Fiddle Proof: http://jsfiddle.net/RNF5T/ Thanks @maja. As @Niko says in the comment, there aren't any associative arrays in JavaScript. You are actually setting properties on the array object, which is not a very good idea. You would be better off using an actual object. var some...