- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Access previously iterated element within array.map in JavaScript?
Let’s say the following is our array −
var details = [ {subjectId:110, subjectName: 'Java' }, {subjectId:111, subjectName: 'Javascript' }, {subjectId:112, subjectName: 'MySQL' }, {subjectId:113, subjectName: 'MongoDB' } ];
Now, use the concept of map(). The code is as follows −
Example
var details = [ {subjectId:110, subjectName: 'Java' }, {subjectId:111, subjectName: 'JavaScript' }, {subjectId:112, subjectName: 'MySQL' }, {subjectId:113, subjectName: 'MongoDB' } ]; var output = details.map((detailsObject, index) => { var tempObject = {}; tempObject.subjectId= detailsObject.subjectId; tempObject.subjectName = detailsObject.subjectName; const getThePreviousObject = index != 0 ? details[index-1] : null; tempObject.previousSubjectName = getThePreviousObject ? getThePreviousObject.subjectName : 'Not Available' return tempObject; }) console.log(output);
To run the above program, you need to use the following command −
node fileName.js.
Here my file name is demo204.js.
Output
This will produce the following output −
PS C:\Users\Amit\javascript-code> node demo204.js [ { subjectId: 110, subjectName: 'Java', previousSubjectName: 'Not Available' }, { subjectId: 111, subjectName: 'JavaScript', previousSubjectName: 'Java' }, { subjectId: 112, subjectName: 'MySQL', previousSubjectName: 'JavaScript' }, { subjectId: 113, subjectName: 'MongoDB', previousSubjectName: 'MySQL' } ]
- Related Articles
- Object.keys().map() VS Array.map() in JavaScript
- Why does Array.map(Number) convert empty spaces to zeros? JavaScript
- How to access Python objects within objects in Python?
- How to Access <tr> element from Table using JavaScript?
- Chunking array within array in JavaScript
- Extract particular element in MongoDB within a Nested Array?
- How to access index of an element in jQuery?
- How to access element with nth index in jQuery?
- C# Program to access first element in a Dictionary
- How to access an array element in C language?
- Prime numbers within a range in JavaScript
- Sorting the numbers from within in JavaScript
- Sorting alphabets within a string in JavaScript
- Armstrong number within a range in JavaScript
- Performing shifts within a string in JavaScript

Advertisements