Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lodash map returning array of objects

i have a arrray of objects where i wish to convert the data from medicine to type string. The only problem is instead of returning the array of objects is returing me the array of medicine.

Example input:

data = [{medicine: 1234, info: "blabla"},{medicine: 9585, info: "blabla"},..]

desired output:

data = [{medicine: "1234", info: "blabla"},{medicine: "9585", info: "blabla"},..]

What im getting? Array of medicine numbers.

Here is my code:

var dataMedicines = _.map(data, 'medicine').map(function(x) {
                return typeof x == 'number' ? String(x) : x;
            });
like image 291
Pedro Avatar asked Jun 16 '16 18:06

Pedro


3 Answers

Lodash is much powerful, but for simplicity, check this demo

var data = [{
  medicine: 1234,
  info: "blabla"
}, {
  medicine: 9585,
  info: "blabla"
}];

dataMedicines = _.map(data, function(x) {
  return _.assign(x, {
    medicine: x.medicine.toString()
  });
});

console.log(dataMedicines);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.2.1/lodash.min.js"></script>
like image 177
Medet Tleukabiluly Avatar answered Sep 17 '22 23:09

Medet Tleukabiluly


Or just a native ES6 solution:

const dataMedicines = data.map(({medicine, info}) => ({medicine: `${medicine}`, info}));

The advantage is that this is a more functional solution that leaves the original data intact.

like image 31
Maurits Rijk Avatar answered Sep 17 '22 23:09

Maurits Rijk


I'm guessing you want "transform" all medicine number to strings?

If that's the case, you don't need to first map.

var dataMedicines = _.map(data, function(x){
    var newObj = JSON.parse(JSON.stringify(x)); // Create a copy so you don't mutate the original.
    newObj.medicine = newObj.medicine.toString(); // Convert medicine to string.
    return newObj;
});
like image 39
ShuberFu Avatar answered Sep 20 '22 23:09

ShuberFu