When working with JavaScript, I have an array of objects containing ids, names, and other properties that I am iterating over to create a new object with modified properties. One specific requirement is that one property should be related to the last iterated element, like its predecessor. For example:
let returnedArrOfObjs = [{id: 1, name: 'first', predecessor: 'none' },
{id: 2, name: 'second', predecessor:'first'},
{id: 3, name: 'third', predecessor: 'second'}]
I am wondering if there is a way to access the previously iterated element?
The code snippet below doesn't work as prevObj is undefined, but it showcases my intention:
array.map(obj => {
let rObj = {};
rObj.id = obj.id,
rObj.name = obj.name,
rObj.predecessor = prevObj ? prevObj.name : 'none'
return rObj;
})