如何从对象数组中按数组挑选元素

时间:2018-11-11 12:05:28

标签: javascript functional-programming lodash

我有一个对象数组,我想删除一些这样的元素。

var data = [{a:1, b:2, c:3, d:4}, {a:11, b:22, c:33, d:44}]
var saveByKeys = ['a', 'c']

我想要的结果是:

var reuslt = [{a:1, c:3}, {a:11, c:33}]

如何使用lodash做到这一点?单行会更好

2 个答案:

答案 0 :(得分:1)

您可以将lodash的_.pick()Array.map()(或lodash的_.map())一起使用:

const data = [{a:1, b:2, c:3, d:4}, {a:11, b:22, c:33, d:44}]
const saveByKeys = ['a', 'c']

const result = data.map(o => _.pick(o, saveByKeys))

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

答案 1 :(得分:0)

如果您想避免使用lodash,这就是ES6的样子:

var data = [{a:1, b:2, c:3, d:4}, {a:11, b:22, c:33, d:44}]
var keys = ['a', 'c']

const pick = (obj, keys) => keys.reduce((r,c) => (r[c] = obj[c], r),{})
console.log(data.map(x => pick(x, keys)))