在对象上使用lodash映射时,如何获取迭代数?

时间:2019-04-18 16:59:51

标签: javascript lodash

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

我需要知道每个循环的迭代次数。我可以手动创建一个变量,然后在每次循环迭代时将其递增,但是我希望使用lodash map方法的某些内置功能。有提示吗?

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++;
});

3 个答案:

答案 0 :(得分:1)

您可以使用Object.entries()Object获取键/值,然后再映射

   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)
})

答案 1 :(得分:1)

使用lodash,您可以使用_.overArgs()生成一个函数,该函数将对象转换为带有_.toPairs()的条目并调用带有条目的_.map()

const { overArgs, map, toPairs } = _;

const mapObjectWIthIndex = overArgs(map, [toPairs]);

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

const newThings = mapObjectWIthIndex(things, ([v, k], index, collection) => {
  if (index === collection.length - 1) return `${v} - last`;
  
  return `${v} - ${index}`;
});

console.log(newThings);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

答案 2 :(得分:0)

我仍然好奇是否有一种方法可以从lodash方法中获取索引,但这是我想出的解决方案,效果很好:

const newThings = Object.entries(things).map(([thingKey, thing], index) => {
  // Do some stuff
  if (index === collection.length - 1) {
    // Do something when it is the last property 
  }
});