繁体   English   中英

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

[英]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

我需要知道每个循环的迭代次数。 我可以手动创建一个变量,然后在每次循环迭代时将其递增,但是我希望使用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++;
});

您可以使用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) }) 

使用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> 

我仍然很好奇是否有办法从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 
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM