我有这种数据,通常是从api那里获取的,这是我第一次使用lodash。
{
"_id": "93866",
"stats": [
{
"points": 86,
"pos": 11,
"createdAt": "2019-01-16T10:13:40.650Z",
"updatedAt": "2019-01-16T10:13:40.825Z"
},
{
"points": 79,
"pos": 26,
"createdAt": "2019-01-16T10:13:40.650Z",
"updatedAt": "2019-01-16T10:13:40.825Z"
},
{
"points": 64,
"pos": 39,
"createdAt": "2019-01-16T10:13:40.650Z",
"updatedAt": "2019-01-16T10:13:40.825Z"
}
]
}
我想要做到的就是
[ [ 86, 11 ], [ 79, 26 ], [ 64, 39 ] ]
通过执行此操作,我可以简单地以本机方式执行此操作,
var result = data.stats.map(o => [o.points, o.pos])
// => [ [ 86, 11 ], [ 79, 26 ], [ 64, 39 ] ]
这会产生预期的结果,但是我正在使用的环境取决于lodash的使用。
到目前为止,我已经尝试过_.map(data.stats, 'points')
,但是我不确定如何做到[ [ 86, 11 ], [ 79, 26 ], [ 64, 39 ] ]
那怎么办呢?
答案 0 :(得分:4)
您可以在函数回调中使用object#destructring
。
let data = {"_id":"93866","stats":[{"points":86,"pos":11,"createdAt":"2019-01-16T10:13:40.650Z","updatedAt":"2019-01-16T10:13:40.825Z"},{"points":79,"pos":26,"createdAt":"2019-01-16T10:13:40.650Z","updatedAt":"2019-01-16T10:13:40.825Z"},{"points":64,"pos":39,"createdAt":"2019-01-16T10:13:40.650Z","updatedAt":"2019-01-16T10:13:40.825Z"}]},
result = _.map(data.stats, ({points, pos}) => [points,pos]);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
答案 1 :(得分:2)
您可以将lodash的_.at()
与_.map()
结合使用:
const data = {"_id":"93866","stats":[{"points":86,"pos":11,"createdAt":"2019-01-16T10:13:40.650Z","updatedAt":"2019-01-16T10:13:40.825Z"},{"points":79,"pos":26,"createdAt":"2019-01-16T10:13:40.650Z","updatedAt":"2019-01-16T10:13:40.825Z"},{"points":64,"pos":39,"createdAt":"2019-01-16T10:13:40.650Z","updatedAt":"2019-01-16T10:13:40.825Z"}]};
const result = _.map(data.stats, o => _.at(o, ['points', 'pos']));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
您还可以使用_.map()
和_.at()
的{{3}}版来创建函数:
const data = {"_id":"93866","stats":[{"points":86,"pos":11,"createdAt":"2019-01-16T10:13:40.650Z","updatedAt":"2019-01-16T10:13:40.825Z"},{"points":79,"pos":26,"createdAt":"2019-01-16T10:13:40.650Z","updatedAt":"2019-01-16T10:13:40.825Z"},{"points":64,"pos":39,"createdAt":"2019-01-16T10:13:40.650Z","updatedAt":"2019-01-16T10:13:40.825Z"}]};
const fn = _.map(_.at(['points', 'pos']));
const result = fn(data.stats);
console.log(result);
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>
答案 2 :(得分:1)
您已经弄清楚了,您只需要结合您的 native 版本和您的lodash
尝试:
var result = _.map(data.stats, o => [o.points, o.pos]);
如您所见,我用您的 native 版本中使用的函数将_.map
(原为'points'
)的第二个参数替换了。
答案 3 :(得分:1)
这里是:
_.map(data.stats, obj => [ obj.points, obj.pos ])
编辑:@Hassan Imam使用解构对象做出了一个有趣的答案