简体   繁体   English

lodash map返回对象数组

[英]lodash map returning array of objects

i have a arrray of objects where i wish to convert the data from medicine to type string. 我有一个对象的arrray我希望将数据从医学转换为类型字符串。 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 Lodash非常强大,但为了简单起见,请查看此演示

 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: 或者只是本机ES6解决方案:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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