我有跟随对象。
var response = {
"driving": [
{
"distance": "10,7 km",
"duration": "28 minutes"
},
{
"distance": "9,8 km",
"duration": "25 minutes"
},
{
"distance": "5,8 km",
"duration": "18 minutes"
}
],
"walking": [
{
"distance": "10,4 km",
"duration": "2 heures 10 minutes"
},
{
"distance": "9,8 km",
"duration": "2 heures 2 minutes"
},
{
"distance": "5,7 km",
"duration": "1 heure 11 min"
}
]
}
我想将此对象转换为如下对象数组:
[{"distance":"10,7 km","walking":"2 heures 10 minutes","driving":"28 minutes"},
{"distance":"9,8 km","walking":"2 heures 2 minutes","driving":"25 minutes"},
{"distance":"5,8 km","walking":"1 heure 11 min","driving":"18 minutes"}]
任何想法如何使用underscore.js实现这一目标?
答案 0 :(得分:1)
var _ = require('lodash');
var response = {
"driving": [{
"distance": "10,7 km",
"duration": "28 minutes"
}, {
"distance": "9,8 km",
"duration": "25 minutes"
}, {
"distance": "5,8 km",
"duration": "18 minutes"
}],
"walking": [{
"distance": "10,4 km",
"duration": "2 heures 10 minutes"
}, {
"distance": "9,8 km",
"duration": "2 heures 2 minutes"
}, {
"distance": "5,7 km",
"duration": "1 heure 11 min"
}]
}
function customizer(objValue, srcValue) {
var object = {
"distance": objValue["distance"],
"driving": objValue["duration"],
"walking": srcValue["duration"]
}
return object
}
console.log(_.mergeWith(response["driving"], response["walking"], customizer));
检查一下,lodash@4.11.2支持这个