简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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