Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lodash pick object fields from array

I have array of objects:

var results= [
    {         
      "_type": "MyType",
      "_id": "57623535a44b8f1417740a13",         
      "_source": {
        "info": {
          "year": 2010,
          "number": "string",             
        },
        "type": "stolen",           
        "date": "2016-06-16T00:00:00",
        "createdBy": "57469f3c71c8bf2479d225a6"            
      }
    }
  ];

I need to select specific fields from array. In result, I want to get the following:

[
    {
        "_id": "57623535a44b8f1417740a13",
        "info": {
            "year": 2010,
            "number": "string"
        },
        "type": "stolen",            
        "date": "2016-06-16T00:00:00",
        "createdBy": "57469f3c71c8bf2479d225a6"
    }
]

As you can see, I want to select _id field and content of _source object. How can I do this with lodash?

I've found .map function, but it doesn't take array of keys: var res = _.map(results, "_source");

like image 987
user348173 Avatar asked Sep 06 '25 16:09

user348173


2 Answers

You could do:

var mapped = _.map(results, _.partialRight(_.pick, ['_id', 'info', 'type', 'date', 'createdBy']));

A little explanation:

  1. _.map(): Expects a function which takes each item from the collection so that you can map it to something else.
  2. _.partialRight(): Takes a function which will be called later on with the its arguments appended to the end
  3. _.pick(): Gets the path specified from the object.
like image 116
radyz Avatar answered Sep 09 '25 07:09

radyz


I had the same requirement, and the below solution worked best for me.

let users = [
{
  "_id": "5ead7783ed74d152f86de7b0",
  "first_name": "User First name 1",
  "last_name": "User Last name 1",
  "email": "[email protected]",
  "phone": 9587788888
},
{
  "_id": "5ead7b780d4bc43fd0ef92e7",
  "first_name": "User FIRST name 1",
  "last_name": "User LAST name 1",
  "email": "[email protected]",
  "phone": 9587788888
}
 ];

users = users.map(user => _.pick(user,['_id','first_name']))

console.log(users)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
like image 32
Hardik Raval Avatar answered Sep 09 '25 05:09

Hardik Raval