Search code examples
javascriptlodash

How can I get the iteration number when using lodash map on an object?


const things = {
  thing1: 'Thing 1',
  thing2: 'Thing 2',
  thing3: 'Thing 3',
};

const newThings = _.map(things, (thing, thingKey) => {
  console.log(thingKey, thing);
}
// Outputs:
// thing1 Thing 1
// thing2 Thing 2
// thing3 Thing 3

I need to know what the iteration number is on each loop. I could manually create a variable and then increment it on each loop iteration, but I was hoping for some built-in functionality of the lodash map method. Any tips?

let iterationNumber = 0;
const newThings = _.map(things, (thing, thingKey, collection) => {
  // Do some stuff
  if (iterationNumber === collection.length - 1) {
    // Do something when it is the last property 
  }
  iterationNumber++;
});

Solution

  • You can use Object.entries() to get key/value from Object and than map

       map (currentValue, index, array)
    

    const things = {
      thing1: 'Thing 1',
      thing2: 'Thing 2',
      thing3: 'Thing 3',
    };
    
    
    Object.entries(things).map(([key,value],index)=>{
      console.log(key,value,index)
    })