11

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;
            });
1
  • 1
    Well, your first _.map(data, 'medicine') strips out and return the medicine number into the next mapping function. Commented Jun 16, 2016 at 18:45

3 Answers 3

16

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>

Sign up to request clarification or add additional context in comments.

1 Comment

is there a way to only have return object with medicine in it that's it, so it would look like [ {medicine: blabla} , {midicine: twoblacla} ]
8

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.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.