Reputation: 19
I have an array of object, and I want to remove some elements like this.
var data = [{a:1, b:2, c:3, d:4}, {a:11, b:22, c:33, d:44}]
var saveByKeys = ['a', 'c']
The result I want is:
var reuslt = [{a:1, c:3}, {a:11, c:33}]
How to use lodash to do that? One-line would be better
Upvotes: 0
Views: 175
Reputation: 18515
If you want to avoid lodash
this is how this would look like with 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)))
Upvotes: 0
Reputation: 191976
You can use lodash's _.pick()
with Array.map()
(or lodash's _.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>
Upvotes: 1