简体   繁体   中英

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?

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/lodash@4.17.15/lodash.min.js"></script>

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)

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"
      }
    ]
  },
}

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