Start from scratch when establishing the baseline for "defaults."

Struggling to reimagine the _.defaults function from underscore.js, I keep encountering this pesky error:

Error message: should copy source properties to undefined properties in the destination object‣ AssertionError: expected { a: 'existing' } to deeply equal { a: 'existing', b: 2, c: 3, d: 4 }

Highlighted are the missing conditions:

-should copy source properties to undefined properties in the destination object and return the updated object

Showcasing my current code snippet:

_.defaults = function (destination, source) {
  Object.keys(destination).forEach(key => {
    if (destination[key] === undefined || destination[key] === null) {
      destination[key] = source[key];
    }
  })
  return destination;

};

Answer №1

When using _.defaults, it's important to note that keys from the source object may not exist in the destination object. This means you should iterate over the keys of the source object rather than those of the destination object:

_.defaults = function (destination, source) {
  Object.keys(source).forEach(key => {
    if (destination[key] === undefined || destination[key] === null) {
      destination[key] = source[key];
    }
  })
  return destination;
};

As a side note, instead of checking x === null || x === undefined, you can simplify it to x == null. This saves some precious keystrokes.

_.defaults = function (destination, source) {
  Object.keys(source).forEach(key => {
    if (destination[key] == null) {
      destination[key] = source[key];
    }
  })
  return destination;
};

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

Creating a Redirect Form that Directs Users to a Specific Page Depending on Input Data

Apologies if this is a basic issue, but I'm struggling to figure it out. I am trying to create a form field on a webpage that will redirect users to a specific page based on the data they input. For example, if someone types in "dave" and submits the ...

Dividing the logic from the Express router while retaining the ability to utilize Express functionalities

As I embark on my journey of developing my first app using Node.js and Express, I have noticed that my router file is starting to get overcrowded with logic. It seems like there is too much going on in there. My solution to this issue is to pass a functio ...

Determining the time variance within a PHP/MySQL/JavaScript platform

Seeking the most efficient method to calculate the time difference from now until a specific point, such as a countdown time. In my scenario, I have an auction with a designated closetime stored in a MySQL record in the format " DATETIME 00-00-000 00:00:0 ...

What is the best way to conceal a callback form once it has been successfully submitted?

In my callback form, everything seems to be functioning properly. However, there is a slight issue when the client hits the submit button multiple times. Each time they do so, a notification saying "Your request sent successfully" pops up next to the butto ...

Encountered an error when attempting to access property 'connect' of an undefined value

I encountered an issue with pg.connect not being defined in the Handler module. My goal is to set up a table using postgres in fastify. In my routes handling folder, I manage the routes and send API requests. The error occurs when I navigate to http://loc ...

Assign the value from JavaScript to the element with the "ng required" attribute, without resetting frm.$error.required to false

My situation involves using a button with ng-style that relies on frm.mybtn.$error.required as follows: ng-style="frm.mybtn.$error.required?{'border-color':'#a94442'}:''" I am updating the value of the button from JavaScript ...

Retrieving data from an anonymous function in AngularJS and outputting it as JSON or another value

Within the following code, I am utilizing a server method called "getUserNames()" that returns a JSON and then assigning it to the main.teamMembers variable. There is also a viewAll button included in a report that I am constructing, which triggers the met ...

Uncovering the jsPlumb link between a pair of identifiers

Could someone help me understand how to disconnect two HTML elements that are connected? I have the IDs of both elements, but I'm not sure how to locate their connection in the jsPlumb instance. Any tips on finding the connection between two IDs? ...

What is the process for updating a particular index in a list?

Currently, I am delving into React by working on a task master app. The concept is simple - each user input becomes a new task in an array of tasks. The app features Add, Delete, and Update buttons for managing these tasks. Everything is functioning smoot ...

Even though there is an error in the line of code saying "Error in render: RangeError: Invalid array length", it still manages to perform its intended task

When trying to round a float number and display stars equal to that rating number, the code works as expected. Surprisingly, it also generates an error Error in render: "RangeError: Invalid array length" <p>Rating: <i v-for='n in Math.round( ...

How can I export an ES Object in Node.JS to an NPM package?

I am currently facing a challenge involving an ES5 object/function that I want to integrate into an NPM package. This particular object is within a namespace defined as MY_NAMESPACE.myObject = function(){...} where MY_NAMESPACE is simply an object. Typic ...

Using jQuery to Extract HTML Content from a JSON Object

I'm completely lost on what I'm doing incorrectly, but the JSON string I have looks like this: jsonp443489({"content":"<!DOCTYPE html><html><head><title>Title</title></head><body><p>Hello World< ...

The Typescript counterpart to PropTypes.oneOf, utilizing a pre-existing variable

While I know this question has been addressed on Stack Overflow here, I still find myself struggling with a similar issue in my TypeScript project. Currently, I am in the process of converting a JavaScript project to Typescript. Within one of my React com ...

interaction between modernizr and ajax causing loading issues

I am currently utilizing modernizr.js and a customized ajax function on my page to refresh the content every x seconds. Below is the snippet of code for the functions being triggered. function reloadSlides() { jQuery.ajax({ url: document.locat ...

Concealing a div depending on the price variation

I'm looking for a way to dynamically show or hide a div based on the price of selected variations in my online store. Let's take a product with options priced at £359 and £455 as an example. In addition, there is a finance plugin with a minim ...

Send data containing special characters through a GET request in PHP

I am looking for a way to send any text as a GET parameter to a PHP script. Currently, I am simply appending the text like this: action.php?text=Hello+my+name+is+bob This URL is generated using JavaScript and then used in an AJAX request. In action.php, ...

Is there a way to prevent a web page from refreshing automatically for a defined duration using programming techniques?

I am currently working on a specific mobile wireframe web page that includes a timer for users to answer a question after the web content body has loaded. There are two possible outcomes when answering the question: 1) If the user fails to answer in time, ...

What is the best way to adjust image size based on different screen sizes while ensuring the buttons at the top remain responsive

How can I make the image and image select and delete buttons responsive? I am looking to eliminate the gap after the delete button. Any suggestions are welcomed. <div class="container mt-0"> <div class="row"> ...

Encountering an issue with double quotes formatting in Spring Boot applications

Currently, I am developing an application where I need to pass data from a Spring Boot controller to a template using Thymeleaf. Everything was going smoothly, until I encountered an issue when trying to send JSON data. I noticed that the double quote (" ...

Utilizing VueJS to Establish a Binding Relationship with Props

One of my Vue components is named Avatar.vue, and it is used to create an avatar image based on user-defined props. The parameter imgType determines whether the image should have rounded corners or not. Here is the code: <template> <div> & ...