
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Creating an associative array in JavaScript with push()?
For this, use forEach() loop along with push(). Following is the code −
Example
var studentDetails= [ { studentId:1, studentName:"John" }, { studentId:1, studentName:"David" }, { studentId:2, studentName:"Bob" }, { studentId:2, studentName:"Carol" } ] studentObject={}; studentDetails.forEach (function (obj){ studentObject[obj.studentId] = studentObject[obj.studentId] || []; studentObject[obj.studentId].push(obj.studentName); }); console.log(studentObject);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo116.js.
Output
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo116.js { '1': [ 'John', 'David' ], '2': [ 'Bob', 'Carol' ] }
- Related Questions & Answers
- Creating an associative array in JavaScript?
- Dynamically creating keys in JavaScript associative array
- JavaScript in filter an associative array with another array
- Sorting an associative array in ascending order - JavaScript
- Updating an array with $push in MongoDB
- Prefix sums (Creating an array with increasing sum) with Recursion in JavaScript
- Length of a JavaScript associative array?
- Looping numbers with object values and push output to an array - JavaScript?
- JavaScript creating an array from JSON data?
- PHP array_push() to create an associative array?
- PHP Pushing values into an associative array?
- PHP Associative Array
- Creating a JavaScript array with new keyword.
- Convert an object to associative array in PHP
- How to use associative array/hashing in JavaScript?
Advertisements