Creating an associative array in javascript: A step-by-step guide

I require an array to be structured in the following manner:

{"3":
    {"label":"All i want for christmas",
     "song":"Alliw_1405399165.mp3",
     "name":"All i want for christmas"},
"4":
    {"label":"Call your girlfriend robyn clip",
     "song":"Gangnam_Style_2.m4a",
     "name":"Call your girlfriend robyn},
"5":
    {"label":"Gangnam style psy clip",
     "song":"Samba_De_Janeiro-world_cup_for_jivebird.m4a",
     "name":"Gangnam style psy clip"} }

These values are to be inserted after receiving an ajax response as shown below:

$.each(response.result, function(i,item){

                        label = item.name;
                        if((item.special_price < item.price)&&(item.special_price!=0) && (item.special_price!=null)) {
                            label += '- is Only '+ item.special_price + item.currencysymbol;
                        }

                        tmpsongList[item.product_id].push({'label': label,
                                                    'song': item.audiofile,
                                                    'name': item.name,
                                                    'tag': item.tag,
                                                    'song_path': item.audio_url});

                });

However, this results in the error Uncaught TypeError: Cannot read property 'push' of undefined

How can I generate an array like this? Any assistance in resolving this issue would be greatly appreciated. Thank you.

Answer №1

append is a function that belongs to lists (not dictionaries) and adds the specified value at the end of the list.

You are not attempting to append a value to the dictionary, but rather to assign it to a particular key.

dictionary[item_id] = { ...

Answer №2

This is not simply an array, it's actually a map or object structure. When you declare var a = {}, it creates an object or map. On the other hand, when you use var a = [], it initializes an array. In your particular scenario, you will need to

tmpsongList[item.product_id] = {'label': label,
                                                'song': item.audiofile,
                                                'name': item.name,
                                                'tag': item.tag,
                                                'song_path': item.audio_url};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Handling a jQuery Ajax success callback when it fails

I am encountering an issue with my ajax post request where even though I have separate success, failure, and status code handlers, when the request fails with a 400 error, part of the success function is still being executed. Can someone provide insight in ...

Exploring First-Person Shooter Rotation with THREE.JS

I recently attempted to create a rotation system for a First Person Shooter game using THREE.JS. However, I encountered a strange issue where the camera would pause momentarily before returning, especially at certain rotations. When checking the rotation ...

"Transferring an array of data to a Laravel controller via AJAX: A step-by-step guide

Is there a way to send arrays of data to the back-end all at once? The Problem 1. This is what I'm currently sending: array:5 [ "_token" => "S5s5ZTTnnP93MyXgCql0l9vhHsiqt5VWaFyEedXj" "product_id" => "21" "specification_id" => "6" " ...

.mouseleave() triggers when exiting a designated boundary area

I'm attempting to implement a roll-up feature for a div when the mouse is over another div. The issue I'm facing is that the roll-up div closes even if the mouse just exits through the bottom border. Is there a way to achieve this using JavaScrip ...

Trigger Object RuntimeError

Initially, I attempted to pass the object :id to the URL and it was successful. However, when I tried to pass the object to the list, I encountered a ReferenceError. index.ejs: <tr> <th class="text-center">AWB NO</th> <th c ...

Discovering collections of vectors that add up to zero

I am working with four arrays, each containing 3 arrays. For example: set1 = [array([1, 0, 0]), array([-1, 0, 0]), array([0, 1, 0]), ...] My goal is to determine the number of combinations of vectors that sum to zero. The current solution involves nested ...

Exploring the possibilities of jQuery with Accordion functionality and creating dynamic multiple menus

Incorporating the Wayfinder and Accordion menus, I have set up a two-level menu structure for the left column. The structure looks like this: <ul class="accordion">: Menu 1 Sub-menu 1.1 Sub-menu 1.2 Sub-menu 1.3 Menu 2 Sub-menu 2 ...

Having trouble downloading the Chip component in Material-UI? Learn how to fix the download issue

I used the UI to upload a file, and now I want to download it either after some time or instantly. I tried implementing this using the <Chip> component, but it's not working. I need assistance in resolving this issue. Uploaded File: const data ...

Why do confirm or alert boxes in Safari on Windows require a double click?

I'm currently working on a simple JavaScript example where I want to display an alert box when an HTML button is clicked in SAFARI. However, I've noticed that it requires a double click to make the alert disappear from the screen. Does anyone ha ...

There seems to be a problem with the JavaScript function as the indexOf property is undefined

function filteredArray(arr, elem) { let newArr = []; Iterating through each element of the multidimensional array. for (let i=0;i<arr.length;i++){ for (let j=0;j<arr[i].length;j++){ If the value matches the argument passed, assi ...

Unable to retrieve class attributes within a function

I have recently started delving into the world of node.js, and I am facing some challenges with a middleware that I created. The purpose of this middleware is to act as an Error handler. However, I am encountering difficulties in accessing properties that ...

Initiating Firebase Configuration

Currently, I have integrated Firebase as the back-end for my app. Here is how my firebase configuration looks: const firebaseConfig = { apiKey: 'xx', authDomain: "xx", databaseURL: "xx", ...

When an option is selected in one dropdown, a list is dynamically populated in another dropdown. However, the entire column then displays the selected row's options in a table format

https://i.stack.imgur.com/q7tMT.png Upon selecting an option from a dropdown within a table row, I make a call to an API to fetch a list of strings into another dropdown field for that specific row. However, the entire column is being populated with that r ...

Using JavaScript for Array manipulations

Here's a string that I want to convert into an array: "["Arr1","Arr2"]" To achieve the desired format, I need to remove the first and last characters so it looks like this: ["Arr1","Arr2"]. I've attempted using the slice function in this wa ...

Retrieve items from a JSON file using Ionic framework's $http.get method

Issue with Console: SyntaxError: Unexpected token { in JSON at position 119 Xcode controller: str="http://www.website.com/user-orders.php?e="+$scope.useremail; $http.get(str) .success(function (response){ $scope.user_orders = response; ses ...

What could be causing my Mocha reporter to duplicate test reports?

I've created a custom reporter called doc-output.js based on the doc reporter. /** * Module dependencies. */ var Base = require('./base') , utils = require('../utils'); /** * Expose `Doc`. */ exports = module.exports = ...

Tips for transferring JSON data to a CodeIgniter view

I have a query regarding how to replace a specific section of my webpage with data returned from the controller. Currently, I have a page that displays movie details directly fetched from the database. My goal is to only display movies of a particular genr ...

In the event that the $state cannot be located, redirect to a different URL using Ui

Our platform is a unique combination of WordPress backend and AngularJS frontend, utilizing ui.router with html5 mode turned on and a base href="/" due to the stack sites being in the root of the site. We are currently facing an issue: 1) Previously, whe ...

What is the best way to refresh a React ES6 component following an AJAX response?

I'm a beginner in React and ES6, trying to create a search field that fetches data as the user types. I want to make an AJAX call using the fetch API when the user types at least 3 characters in the field. When I run the fetch snippet code in the brow ...

eliminating attributes from a JavaScript object

Seeking a method to strip object properties before sending them to the front-end. Why does this code work as intended: var obj = { name: 'cris', age: 22, } console.log(obj) //displays name and age delete obj.name console.log(obj) //dis ...