Alternative to Lodash for performing a check operation in JavaScript and assigning a new value

Recently, I've been utilizing a code snippet to verify the value of an input field located at index:1 within an array. The code looks like this:

const inputValue=journeyData && journeyData.birthdate && journeyData.birthdate[0]
          ? journeyData.birthdate[0]
          : null, 

I am now curious if there is a lodash alternative that can achieve the same outcome more succinctly?

Answer №1

Utilize the built-in optional chaining feature instead of relying on lodash.

const journeyData = { birthdate: [new Date()] };

const inputValue = journeyData?.birthdate?.[0] ?? null;
const inputValue2 = journeyData?.birthdate?.[2] ?? null;

console.log(inputValue);
console.log(inputValue2);

For further reference, check out:

Answer №2

If you're looking to retrieve values from nested objects in JavaScript, one handy approach is using the _.get() function provided by Lodash library. It allows you to specify a path along with a fallback value in case the specified path doesn't exist:

function fetchValue(data) {
  const result = _.get(data, "address.street[0]", null);
  return result;
}

console.log( fetchValue() );                    // null
console.log( fetchValue({}) );                  // null
console.log( fetchValue({ address: {} }) );     // null
console.log( fetchValue({ address: { street: [123] } }) ); // 123
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5c3033383d2f341c68726d6b726e6d">[email protected]</a>/lodash.min.js"></script>

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

Arrange the array based on the order of the enumeration rather than its values

Looking to create an Array of objects with enum properties. export enum MyEnum { FIXTERM1W = 'FIXTERM_1W', FIXTERM2W = 'FIXTERM_2W', FIXTERM1M = 'FIXTERM_1M', FIXTERM2M = 'FIXTERM_2M', FIXTERM3M = 'FIX ...

Steps for transferring a checked statement from an HTML document to a JavaScript file

Struggling to transfer checked statements from HTML to JS file {{#each readValues }} <br> Plug: {{@index}} => {{this}} <input type='checkbox' class="plug" onclick="sendData();" /> {{/each}} The code above is written i ...

The initialization of a static member in a JS class occurs prior to the loading of the cdn

After declaring this class member, I encountered the issue stating that MenuItem is not defined. It appears that the class initialization occurs before React or Material-UI finishes loading (I am currently loading them from their CDN using straight < ...

Tips for identifying visible elements on a webpage with JavaScript

My #diagram div is larger than the visible area in my browser and contains up to 1500 "boxes" as div elements. I am looking for a way to determine which of these 1500 boxes are actually visible to the user so that I can dynamically load them using ajax. Cu ...

How can you verify the value of a disabled HTML input element in TestCafe using Typescript?

TestCafe Typescript - how to verify the value of a disabled HTML input element? Despite being disabled for user interaction, I want to ensure that this element still holds the anticipated value. example public async checksomething(text: string) { co ...

Combine es6 imports from the identical module using an Eslint rule or plugin

Looking to consolidate my ES6 imports from a single module into one for my React project. For example: import { Title } from "@mantine/core"; import { Center } from "@mantine/core"; import { Divider } from "@mantine/core"; T ...

I am hoping for JavaScript to perform three distinct actions depending on the names of the files that are currently open in Photoshop

Currently, I am in the process of developing a JavaScript script for Photoshop. The main objective of this script is to prompt the user to choose a folder containing multiple files. Subsequently, the script will open each file within the folder and perform ...

Engage with and rearrange JSON data

Upon receiving data from the endpoint, I realized that it needed some modifications before being suitable for display in a table. The initial example data looks like this: const data = [ { Year: 2017, OriginalIntBalanceOverdue: 0.0, D ...

Steps to retrieve component values within the same component

I am currently working on developing a React component where I need to manage the checked status of checkboxes and select options when a change event occurs. However, I am unsure of how to retrieve the value of the checked checkboxes and update the state a ...

Having issues with v-for in Vuejs? It seems to be looping multiple times

<div v-for="item in items" :key="item.id"> <div v-for="accordion in accordions" :key="accordion.title" class="line" :class="{ green: accordion.text === 'AllaboutVue', red: accordi ...

The order of console outputs can be inconsistent and may not always align with the order in which they are called

Hello there! I'm diving into the world of JavaScript and have a query to share on Stackoverflow. If something seems missing in my question, please do point it out for me. Question 1: Can someone shed light on why the output sequence in the console s ...

Securing Credit Card Numbers with Masked Input in Ionic 3

After testing out 3-4 npm modules, I encountered issues with each one when trying to mask my ion-input for Credit Card numbers into groups of 4. Every module had its own errors that prevented me from achieving the desired masking result. I am looking for ...

Using JS to switch between text and state in ToneJS

I am facing an issue with the text not displaying in the "play-stop-toggle" element, despite my limited experience with JS. My desired outcome includes: [SOLVED] The text in <div id="play-stop-toggle" onclick="togglePlay()">Play ...

Persisting a single module using vuex-persistedstate

Is there a way to configure vuex-persistedstate so that only one module persists state through page refresh? Currently, when I use plugins: [createPersistedState()] inside the user module, it does not work. plugins: [createPersistedState()] only works wh ...

The `introJs()` API encounters issues when connected to an element within a jQuery modal dialog box

I am attempting to showcase an Intro.js tour on a specific element located within a <table>. This particular <table> is nested inside a dialog box created using jQuery UI. The rows of the table are dynamically inserted using JavaScript: while ...

Guide to selecting a checkbox using its unique identifier with a specific key press

Does anyone know how to create a script that will automatically click a checkbox when the 'c' key is pressed? I would appreciate any guidance or assistance in creating this script. This is the desired functionality: $("#cHideChat").click(); ...

Learn how to cycle through three different texts that appear in the same spot using smooth transitions

I am working with three different rows that contain the Typography component. My goal is to display the first row, followed by the second, then the third, and back to the first one in a continuous loop. All three rows should be shown in the same location, ...

What is the best way to showcase a single item from an array in Vue.JS?

Suppose I have a list of items in Vue.JS data () { return{ items: [ { itemID: 5, itemText: 'foo' }, { itemID: 3, itemText: 'bar' } ] } } Now, if I want to show the item with the itemID of 3 i ...

Using JavaScript, extract individual objects from a JSON object

Recently, I've been tasked with displaying items from a JSON-file in a well-organized manner. However, the format of the JSON file is unfamiliar to me. The code snippet provided below pertains to this task: function readFile(file) { var rawFile = ...

Vue.js - The error message "$slots have 'el' is null" indicates a problem with the element in

When trying to access the Vuejs $slots instance, I encounter el = null, but type = "div" Here is the template: <slot name="head"> <h1> {{ text }} </h1> </slot> And in the script section: ... ...