user1107173 user1107173 - 1 month ago 10
Javascript Question

underscore.js: _.pick to extract properties inside an object that's in an array

Below is the object that I have:

{
"email": "joe@example.com",
"id": null,
"firstName": null,
"lastName": null,
"createdAt": "2016-10-05T18:16:07.000Z",
"updatedAt": "2016-10-05T18:16:07.000Z",
"Details": [
{
"id": 1,
"token": null,
"deviceId": null,
"code": 12345678,
"verified": null,
"createdAt": "2016-10-05T18:16:07.000Z",
"updatedAt": "2016-10-05T18:16:07.000Z",
"UserEmail": "joe@example.com"
}
]
}


I am hoping to use the pick method from the underscore.js library and return the following object:

{
"email": "joe@example.com",
"firstName": null,
"lastName": null,
"Details": [
{
"token": null,
"deviceId": null,
"code": 12345678,
"verified": null,
}
]
}


I have tried using:

var modifiedObj = _.pick(obj, 'email', 'firstName', 'lastName');


which returns:

{
"email": "joe@example.com",
"firstName": null,
"lastName": null
}


How do I extract the
Details
object and only some of the
properties
inside it?

Answer

Rather than picking at multiple levels, I'd just do

var obj = {
  "email": "joe@example.com",
  "id": null,
  "firstName": null,
  "lastName": null,
  "createdAt": "2016-10-05T18:16:07.000Z",
  "updatedAt": "2016-10-05T18:16:07.000Z",
  "Details": [
    {
      "id": 1,
      "token": null,
      "deviceId": null,
      "code": 12345678,
      "verified": null,
      "createdAt": "2016-10-05T18:16:07.000Z",
      "updatedAt": "2016-10-05T18:16:07.000Z",
      "UserEmail": "joe@example.com"
    }
  ]
};

var newObj = (({email, firstName, lastName, Details}) =>
  ({
    email, 
    firstName, 
    lastName,
    Details: Details.map(
     ({token, deviceId, code, verified}) => ({token, deviceId, code, verified}))
  })
)(obj);

console.log(newObj);

Comments