Tips on extracting values from an array of object properties using lodash

I am working with the following object:

 { 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'} ] }

My goal is to extract the Id, roles.Name, and Events.Id using lodash:

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

However, I am only able to retrieve the Id with the above method.

Can someone guide me on how to achieve this with lodash?

Answer №1

const result = {
   identifier: data.Id,
   userRoles: _.map(data.roles, 'Name'),
   eventIds: _.map(data.Events, 'Id')
};

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'} ]
}

result = {
   identifier: data.Id,
   userRoles: _.map(data.roles, 'Name'),
   eventIds: _.map(data.Events, 'Id')
};


console.log(result);
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5935363d382a31196d77686e77686c">[email protected]</a>/lodash.min.js"></script>

Answer №2

After reviewing information on deep picking from a source here, it appears that using _.pick alone is not sufficient for deep picking tasks. The recommended approach involves utilizing 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)

Answer №3

Uncertain if this approach is optimal, but here is what I have accomplished so far:

Credit goes to @marco-a

After reviewing this solution, I devised the following function:

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

Here is my current solution:

  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 resulting output is:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determining the maximum number within an array using JavaScript

Similar Question: How can I identify the largest number in a JavaScript array? I'm facing issues with this piece of code. Despite spending some time on it, I can't seem to make it work properly. The console only shows 0 when I run it. Can som ...

Multi-line input in ExtJs

Is there a way to create a multiline input with vertical scrollbars in EXTJS? I tried the following code: noteField = new Ext.form.TextField({ emptyText: 'note...', multiline: true, applyTo: &apos ...

Issues encountered with the functionality of face-api and tensorflow.js within the browser

I've been trying to execute this example in the browser Check out the example here Specifically looking at this code snippet <!DOCTYPE html> <html> ... (Contents of the code snippet) ... </body> </html> Unfortunately, I&apos ...

AngularJS dropdown with multiple selections within a Bootstrap modal

Being new to AngularJS, I apologize for asking this question in advance. I am utilizing Angular bootstrap modal from the following link: https://angular-ui.github.io/bootstrap/ and multiple select dropdown list from: https://codepen.io/long2know/pen/PqLR ...

Implementing AJAX notifications in a contact form integrated with PHP, Google reCAPTCHA, and SweetAlert

I've implemented an AJAX script to handle the submission of a basic contact form with Google reCAPTCHA at the end of my HTML. Here's the relevant HTML code: <div class="col-md-6"> <form role="form" id="form" action="form.php" method ...

Unable to get jQuery date picker to function on dynamically generated input fields through ajax

I'm facing an issue with my jQuery date picker not working on an input field generated via Ajax from the server-side, but it works fine when the field is directly added to the page. Here's a simplified version of what I'm dealing with: The ...

Issue encountered when attempting to connect an external script to a Vue single file component

Struggling to link an external script to a single file component in Vue. My project setup is as follows: https://i.sstatic.net/LWvNx.png I need to link the file components/Sshy to ../javascripts/ I have successfully linked other scripts using either of ...

Is there a method to implement colorPicker in an Angular WYSIWYG directive without utilizing jQuery?

After removing the jQuery reference, the color picker is no longer functioning in the WYSIWYG directive. In my project, I am avoiding the use of jQuery, so is there a way to achieve this without using jQuery? Alternatively, are there any other editors av ...

Regular expressions tend to capture an extra symbol beyond what is required

How can I extract numbers from a string? var ss = klase.match(/[col-lg-]\d+/); When trying to extract the number, it retrieves -1 instead of just 1. Why is this happening? An example string: draggable ui-draggable ui-draggable-handle dragged col-l ...

The issue that arises is that only the initial button is able to successfully trigger the opening of

My goal is to create a forum where users can reply to posts by clicking on a "Reply" button that triggers a Bootstrap modal. However, I am facing an issue where the modal only opens when clicking on the first button in a row due to it being placed within a ...

Service running in the background in React Native

In the process of creating a React Native application, I am looking to retrieve data from the web every quarter of an hour. The method I choose should be capable of fetching data in the background while being compatible across multiple platforms. Is ther ...

Processing JSON Serialization from Controller to AJAX Response

I'm struggling to find the correct way to use an HttpWebRequest, and then convert its response into a readable format of JSON for a JavaScript AJAX function. If I just return the raw text, it includes escaping slashes in the response. If I deserializ ...

Adding class name to alternate posts in Next.js

I am currently working on a project with nextjs where I am attempting to fetch a list of images. I want to dynamically add a class based on a condition. Specifically, for every even post, I want to add the class name "mt10". Below is the code snippet I am ...

Having an issue where my meshes disappear when using the Unreal Bloom render pass in ThreeJS. Any ideas on what might be causing

Just starting out with Three and I'm really enjoying it, but I seem to be stuck on a problem. The code in this gist might help: https://gist.github.com/TheeBryanWhite/a7a2041fc8848a0ba449897883c43bdc Initially, the first render functions correctly b ...

Increasing a value in Mongo DB with a conditional statement in a Meteor application

This seemingly simple issue has been causing me some trouble. With the code provided below, I am able to increase or decrease the number of likes on my posts by 1. I am looking to achieve the following: If postLikes = 0, then prevent further reduction o ...

Sending radio button value via AJAX request

Greetings and thank you for taking the time to hear out my query. I am aware that this question has been asked numerous times before (as informed by SO) but my case is slightly unique. I currently have a functional AJAX script that utilizes a dropdown menu ...

What is the best way to restrict user input to specific numbers only?

I have a text input field, how can I ensure that only numeric values from 1 to 31 are allowed? <input type="number" min="1" max="31"> ...

When trying to make edits, the cursor automatically jumps to the end of the field

In Safari, there is a strange issue occurring with a text field used for emails. When entering text and trying to edit by moving the cursor, new characters are automatically placed at the end of the text. It seems that the problematic code causing this beh ...

The search functionality in the bootstrap-select component is failing when the data token includes only numerical values, such as "4730"

Utilizing to create search options for form selection. The search feature works for all strings except those containing numbers such as "4730". Data is loaded into the select tag from a JSON. Here's an example of the select tag: <div class="col- ...

The issue with calling Ajax on button click inside a div container is that the jQuery dialog box is

Here is the code for my custom dialog box: $("#manageGroupShow").dialog({resizable: false, draggable: false, position:['center',150], title: "Manage Group", width:"50%", modal: true, show: { effect:"drop", duration:1000, direction:"up" }, hide: ...