What causes lodash's mapValues to fail when using _.first as a callback function?

Trying my hand at converting some code:

var data = { 1234: [{ name: "obj1" }], 3456: [{ name: "obj2" }] };

I want it to look like this:

{ 1234: { name: "obj1" }, 3456: { name: "obj2" } }

(single items, not arrays).

I discovered that:

_.mapValues(data, function(arr) { return _.first(arr); })

works perfectly. But I'm puzzled why the following isn't sufficient:

_.mapValues(data, _.first)

Instead, it outputs:

{ 1234: [], 3456: [] }

Answer №1

When using _.mapValues, the callback function receives more than just one argument. To make your first example equivalent to the second one, you should use the following code:</p>

<pre><code>_.mapValues(stuff, function() { return _.first.apply(this, arguments)})

Check out this link to see that the arguments passed to the callback function include keyValue, keyName, and the stuff object.

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

Utilizing various camera set-ups within Three.js

How can I smoothly switch between two different cameras in Three.js while transitioning from one to the other? Imagine a scene with a rock and a tree, each having its own dedicated camera setup. I'm looking for a way to seamlessly transition between ...

Struggling to Retrieve Specific Keys for Individual Values in Firebase with React Native

I am currently experiencing difficulty obtaining a unique key for each value in the 'users1' table. firebase.database().ref('users1').once('value').then(snapshot => { var items = []; snapshot.forEach((child) => { ...

Retrieving the elapsed time in seconds from a timer function and displaying it in my

I'm looking to transfer the minutes and seconds from my template's timer to my view. I've experimented with various approaches using an ajax.post request, but it hasn't quite worked as expected. Here is a snippet of my template code: ...

Using Angular to store checkbox values in an array

I'm currently developing a feature that involves generating checkboxes for each input based on the number of passengers. My goal is to capture and associate the value of each checkbox with the corresponding input. Ultimately, I aim to store these valu ...

Error: The function $(...).maxlength is not recognized - error in the maxlength plugin counter

I have been attempting to implement the JQuery maxlength() function in a <textarea>, but I keep encountering an error in the firefox console. This is the code snippet: <script type="text/JavaScript"> $(function () { // some jquery ...

Tips for loading a webpage directly to the center instead of the top position

Is there a way to make the page open at a specific div halfway down the page instead of starting from the top? Here is an example: <div id="d1"> <div id="d2"> <div id="d3"> <div id="d4"> <div id="d5"> <div id="d6"> Do ...

Why does the AngularJS ngRepeat filter permanently remove null values?

Check out this JSFiddle demonstration I created to illustrate the problem: http://jsfiddle.net/s6Lj2/2/ Observe that in the dataset $scope.places = [{ name: 'Chicago', status: 'Active', analyst: 'Sam', recor ...

Eliminate items from a 2-dimensional Numpy array using a specified list

Thank you for taking the time to review my post. In my code, I have a two-dimensional np.array named actions with a shape of (2,x) that contains integers. Additionally, there is another one-dimensional np.array called keys. The elements in this array are ...

Creating empty arrays that are named based on the elements in a separate list

I am looking to create arrays by taking a list and including the items in another array. I have attempted the following: def GenerateArray(pers): for item in pers: (newtest30 + str(item)) = [] (newtest60 + str(item)) = [] (newt ...

Getting a "SyntaxError: Unexpected end of input" error while using jQuery ajax with valid JSON

The PHP response in JSON format shows: {"success":0,"message":"Error: No entityId passed!"} However, my JavaScript code throws an error "SyntaxError: Unexpected end of input". PHP: ... //check if an image id was passed for removal in the POST ...

Ways to store data in the localStorage directly from a server

I'm facing an issue - how can I store data in localStorage that was received from the server? Should I use localStorage.setItem for this purpose? And how do I handle storing an array in localStorage? Or am I missing something here? import { HttpCli ...

Creating a dynamic line in Three.js that connects the closest vertices from two models

I am facing a challenge with loading two models into a scene using OBJloader and the Three.JS library. Some of the models are billboarded by using model.setRotationFromQuaternion( camera.quaternion ); My main objective is to create lines connecting a vert ...

Creating a 2D array in C with strings of a specified length

Currently, I'm working on creating a function that can accept a string (e.g. "Hello I am on stackoverflow") and then print out that string based on a specified width parameter. For example, if the width is set to 10, the output would appear like this: ...

Trouble transferring $rootScope.currentUser between AngularJS profile and settings page

I am in the process of setting up a site using Angular, Express, Node, and Passport. Currently, I am configuring Angular to monitor the $rootScope.currentUser variable with the following code: app.run(function ($rootScope, $location, Auth) { // Watch ...

What steps can be taken to resolve the vulnerability in webpack-pwa-manifest?

Looking for solutions to address the [email protected] and minimist vulnerability. I attempted removing node/modules and package-lock.json, followed by a fresh npm installation, but the issue persists. Any suggestions would be greatly appreciated. Scr ...

What is the best way to align text in the center of a div?

I just created this dropdown menu, but I am encountering an issue. Whenever I resize the div or h4 element, the text ends up at the top. Even after trying to solve it with text-align: center;, the problem persists. Here is a visual representation of what ...

Having difficulty locating the index of the column labeled `Clients` within a table; the result being -1

Having some trouble locating the index of the column name Customers within a table using jQuery/javascript. No matter what I try, it always returns -1 let tableDatacy = "Results_Table"; let columnName = "Customer"; let tableHeaders = [] ...

Changing in height by utilizing javascript's style.height animation

When attempting to adjust the height property using JavaScript instead of jQuery, a challenge arises. The issue lies in the inability to reset the height back to zero after setting it to the scrollHeight of the element. The following is the JavaScript cod ...

The onSubmit function is resistant to updating the state

Currently, I am facing a challenge while working on a form using Material-UI. The TextField component is supposed to gather user input, and upon submission, my handleSubmit() function should update the state with the user-entered information. Unfortunate ...

Tips for accessing basic information from these websites without encountering CORS issues

Having issues retrieving data from the following two sites: and Eurolottery. The CORS issue is causing the problem, and I was able to retrieve data using a Chrome CORS extension and the provided code below: var HttpClient = function() { this.get = fu ...