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;
});
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>
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.
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With