在JavaScript中访问array.map中以前迭代的元素?
假设以下是我们的数组-
var details = [ {subjectId:110, subjectName: 'Java' }, {subjectId:111, subjectName: 'Javascript' }, {subjectId:112, subjectName: 'MySQL' }, {subjectId:113, subjectName: 'MongoDB' } ];
现在,使用的概念map()
。代码如下-
示例
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);
要运行上述程序,您需要使用以下命令-
node fileName.js.
在这里,我的文件名为demo204.js。
输出结果
这将产生以下输出-
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' } ]