Search code examples
javascriptassociative-arrayshift

Javascript SHIFT and POP on Associative Array


Using a regular array I am able to grab the image src from an array using shift() and pop(); I would like to do the same thing using an associative array to add a name and id.

Single Array

var products = ['product1.jpg'];
$('#products').append('<img src="' + products.shift() + '">');

Associative Array

var products = [{id:'1',name:'product 1',image:'product1.jpg'}];
$('#products').append('<img id="' + products.shift() + '" name="' + products.shift() + '" src="' + products.shift() + '">');

Solution

  • This line: var products = [{id:'1',name:'product 1',image:'product1.jpg'}]; declares an array with a single value inside. The single value is an object with the properties id, name, and image. When you call shift on the array, the value returned will be this object.