Javascript lodash 映射返回对象数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37867057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
lodash map returning array of objects
提问by Pedro
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;
});
回答by Medet Tleukabiluly
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>
回答by Maurits Rijk
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.
优点是这是一个功能更强大的解决方案,可以完整保留原始数据。
回答by ShuberFu
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;
});