Creating an associative array in JavaScript with push()?

JavascriptWeb DevelopmentObject Oriented Programming

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' ] }
raja
Published on 09-Sep-2020 16:48:40
Advertisements