- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to generate array key using array index – JavaScript associative array?
For this, use forEach() along with [] to an associative array.
Example
Following is the code −
var result = {}; var names = ['John', 'David', 'Mike', 'Sam', 'Bob', 'Adam']; names.forEach((nameObject, counter) => { var generatedValues = { [nameObject]: counter }; Object.assign(result, generatedValues) }) console.log(result);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo290.js.
Output
This will produce the following output on console −
PS C:\Users\Amit\javascript-code> node demo290.js { John: 0, David: 1, Mike: 2, Sam: 3, Bob: 4, Adam: 5 }
Advertisements