-1

I have this: [{id: '1', name: 'name1'},{id: '2', name: 'name2'}...]

I would like to convert the id field to an integer instead of a string. What’s the most elegant way of doing it using loash?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
sammiwei
  • 3,140
  • 9
  • 41
  • 53
  • 2
    The "most elegant way" is a matter of opinion. What's wrong with the way you're doing it currently? –  Aug 05 '16 at 21:00
  • Possible duplicate of [Map over object preserving keys](http://stackoverflow.com/questions/19023226/map-over-object-preserving-keys) — it’s effectively this but with `return Number(v);`. – Sebastian Simon Aug 05 '16 at 21:03

3 Answers3

1

Loop over the array with _.forEach() and convert the ID to an integer with parseInt().

_.forEach(yourArray, function(obj) {
    obj.id = parseInt(obj.id, 10);
});
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

I'm not familiar with lodash but if it's not an issue with your syntax then make a temporary array for storage and use parse int

Edmazing
  • 84
  • 5
0

I know this isn't lodash but you can do this easily in vanilla ES6:

const newArr = oldArr.map(({id, name}) => ({id: Number(id), name});

https://repl.it/@RemLampa/WiltedHospitablePatch

Rem Lampa
  • 451
  • 6
  • 6