CodingLittle
CodingLittle

Reputation: 1857

How to get values from object property array with lodash?

I have the following obj:

 { Id: '11ea9563-1a4c-c21b-904f-00ff98e8d5ab',
  Email: 'Email',
  Password:
   { type: 'Buffer',
     data:
      [ Buffer value] },
  roles: [ { Name: 'Developer', userroles: [Object] } ],
  Events:
   [ { Id: '11ea9556-c025-39ae-904f-00ff98e8d5ab'} ] }

I want to get the Id, roles.Name and Events.Id with lodash:

_.pick(obj, ['Id', 'roles.Name', 'Events.Id']),

But with the above I only manage to get the Id.

How can I accomplish this with lodash?

Upvotes: 1

Views: 2171

Answers (3)

user125661
user125661

Reputation: 1568

const answer = {
   id: obj.Id,
   roles: _.map(obj.roles, 'Name'),
   events: _.map(obj.Events, 'Id')
};

const obj = { 
  Id: '11ea9563-1a4c-c21b-904f-00ff98e8d5ab',
  Email: 'Email',
  Password: {
    type: 'Buffer'
  },
  roles: [ { Name: 'Developer', userroles: [Object] } ],
  Events:
   [ { Id: '11ea9556-c025-39ae-904f-00ff98e8d5ab'} ]
}

answer = {
   id: obj.Id,
   roles: _.map(obj.roles, 'Name'),
   events: _.map(obj.Events, 'Id')
};


console.log(answer);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

Upvotes: 2

Marvin Kang&#39;
Marvin Kang&#39;

Reputation: 198

From what I have read here, You can't use _.pick for deep picking. Use a combination of _.get and _.map

var _ = require("lodash")

const data = {
  Id: '11ea9563-1a4c-c21b-904f-00ff98e8d5ab',
  Email: 'Email',
  Password: { type: 'Buffer' },
  roles: [
    { Name: 'Developer', userroles: [Object] }
  ],
  Events: [ { Id: '11ea9556-c025-39ae-904f-00ff98e8d5ab' } ]
}

var result = {
  Id: data.Id,
  Email: data.Email,
  'roles.Name': _.map(data.roles, 'Name'), /* Returns expected array of object values */
  'roles.Name': _.map(data.roles, o => _.pick(o, ['Name'])), /* Returns expected array of object */
  'Events.Id': _.map(data.Events, 'Id'),
};


console.log(result)

Upvotes: 2

CodingLittle
CodingLittle

Reputation: 1857

Not sure if this is the best answer for this but right now Ive done the following:

Thanks to @marco-a

I analyzed this answer and came up with the following:

const deepPick = (paths, obj) => _.fromPairs(paths.map(p => [_.last(p.split('.')), _.get(obj, p)]));

My own solution so far:

  const data = _.pick(obj, ['Id', 'roles', 'events']);

  const userRoles = data.roles.map(role=> deepPick(['Name'], role));

  const eventIds = data.events.map(eventId=> deepPick(['Id'], eventId));

The output becomes:

{
    "id": "11ea9563-1a4c-c21b-904f-00ff98e8d5ab",
    "roles": [
      {
        "Name": "Developer"
      },
      {
        "Name": "Admin"
      }
    ],
    "events": [
      {
        "Id": "11ea9556-c025-39ae-904f-00ff98e8d5ab"
      }
    ]
  },
}

Upvotes: 1

Related Questions