Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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' ] }Advertisements