0

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

2
  • 1
    Which lodash methods did you try? The documents give examples for each method including ones that do what you are asking Commented Nov 11, 2018 at 12:08
  • Welcome to SO. You might find reading the site help section useful when it comes to asking a good question. To get the best answers to your question we like to see a) that you've attempted to solve the problem yourself first, and b) used a minimal reproducible example to narrow down the problem. Asking SO to do all the work for you doesn't help you or us. Here's a question checklist you might find useful.. Commented Nov 11, 2018 at 12:18

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.