简体   繁体   中英

How to pick elements by array from array of object

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

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> 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM