Implementing Conditional Value Assignment in JavaScript

When a specific id is received, I need to assign a value to my variable based on the condition that this id matches any of the ids in an array.

For instance, consider the following array:


      {
         key: value,
         key: value,
         direccion:[{
            direccionId: 40,
            calle: "string"
         },{
            direccionId: 41,
            calle: "string2"
         }]
      }
   

In the function AgregarInfo(direccionId), I retrieve the information from 'this.editedItem.direccion' and check if there is any match between the given 'direccionId' and 'infoDireccion'. If a match is found, then the respective 'calle' values are assigned to 'this.editarCliente.txtCalle'.

Am I approaching this task correctly, or is there a more efficient method to achieve the same outcome?

Answer №1

If you're looking for a more efficient solution, consider using the find() method instead of using some() and then looping to find the item. Utilizing find() allows you to accomplish both tasks in one step — the condition will depend on whether find() returns anything, and the value will be the item that was found:

let editedItem = {
    key: 'value',
    otherkey: 'value',
    direccion:[{
     direccionId: 40,
     calle: "string"
    },{
     direccionId: 41,
     calle: "string2"
    }]
 }
 
 function AddInfo(direccionId){
         var infoDireccion = editedItem.direccion;            
         let found = infoDireccion.find(item => item.direccionId === direccionId)
         let editClient = found ? found.calle : undefined
         return editClient
} 

console.log(AddInfo(40))
console.log(AddInfo(41))
console.log(AddInfo(42)) // will return undefined if there's no entry with id 42

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

Embedding the local host into a href link in NextJS

After creating a menu with the Link component in NextJs using href=#contact, I encountered an issue. When I use querySelector on this a element, the href unexpectedly changes to http://localhost:3000/#contact', preventing me from scrolling to that sec ...

Can we specify custom keys to use instead of "label" and "value" in the CSelect component of CoreUI for Vue?

When using CoreUI's CSelect component, the documentation specifies that the "options" property should be an array of objects with the "label" and "value" keys. CSelect API I'm curious if there is a way to specify different keys other than "label ...

What is the method for displaying an array in JavaScript?

When a user clicks the value 3 input box, three input boxes will appear where they can enter values. However, when trying to submit the array, no elements are printed and an error message "Element is not defined" appears. var arr = [0]; function get_va ...

Utilizing Vue's Watch Functionality in Conjunction with the Get and Set Composition API

I am currently working on a project that involves creating a searchable table element with the ability for users to filter and search the displayed results. However, I am encountering some difficulties in setting the value in the computed property setter. ...

Issue: The base type of member reference 'candidate[9]' is not a structure or union. Attempting to use mergesort(candidates.votes, 0, MAX-1, candidates.name) is causing this error

I've just started learning programming and I'm currently working through the CS50 course on edx. I'm now on week 3 and trying to create a simple vote counter program, but I keep encountering an error on line 65. The error message reads: "pl ...

Determine the number of elements chosen within a complex JSON structure

I need to figure out how to count the length of a jsonArray, but I'm stuck. Here's an example to start with: https://jsfiddle.net/vuqcopm7/13/ In summary, if you click on an item in the list, such as "asd1", it will create an input text every t ...

What is the best way to display all HTML content using PHP?

I have an HTML page with a multitude of CSS and JavaScript tags in its head section. My goal is to print them as they are on a PHP page. I've attempted using PHP echo file_get_contents("html_url"); and the fread function. The PHP page successfully loa ...

What is causing the router.events to not fire for FooComponent in my Angular project?

Upon opening the following link , the eventsFromFoo entries in the console are nowhere to be found. It appears that this.router.events is failing to trigger for FooComponent. Any insights on why this might be happening? I am in urgent need of capturing t ...

Is it possible to export CSS stylesheets for shadow DOM using @vanilla-extract/css?

I have been exploring the use of @vanilla-extract/css for styling in my React app. The style method in this library exports a className from the *.css.ts file, but I need inline styling to achieve Shadow DOM encapsulation. During my research, I came acros ...

Updating a .txt file using JavaScript

Is there a method on the client side to add text to a file called text.txt using JavaScript? In Python: f = open("text.txt","w") f.write("Hello World") f.close() The code snippet above would input "Hello World" into the text file. I am looking for a sim ...

Transforming a JavaScript map into an array of objects

Given a map of key value pairs that I cannot control, I am tasked with converting them into an array of objects in a specific format. let paramArray1 = []; let paramArray2 = []; paramArray1.push({username:"test"}) paramArray1.pu ...

How can we utilize CSS floats to achieve maximum widths?

I currently have 5 divs that I need to structure in a specific way: Each div must have a minimum size of 100px The parent container should display as many divs as possible on the first row, with any remaining divs wrapping to new rows if necessary If the ...

Can a JavaScript function be used with images to operate across multiple elements?

How can I make a function work on multiple elements? let image = document.getElementById("opacityLink"); image.onmouseover = function() { image.style = "opacity:0.9"; }; image.onmouseout = function() { image.style = "opacity:1"; }; <div class=" ...

Tips on transferring information between various templates

I need help with creating a chat feature and transferring data between templates. Specifically, I am having trouble clicking on an item in one template, getting the data, and sending it to another template from #template1 to #template2. const app = new Vu ...

Why do `setTimeout` calls within JavaScript `for` loops often result in failure?

Can you help me understand a concept? I'm not inquiring about fixing the code below. I already know that using the let keyword or an iffe can capture the value of i. What I need clarification on is how the value of i is accessed in this code snippet. ...

vuejs v-validate custom validation rule: The maximum value entered by the user must be greater than the minimum value

Here is the code I have for two input fields in vuejs. Currently, both fields require numeric inputs as per the validation rule. If you refer to the official documentation, you can find more information. I want to introduce a new rule where the max-amount ...

error fetching data: unable to access due to client blocking

Despite including all possible information in my request, I am still encountering the same error. How can I identify the root cause of this issue? I have already disabled my AdBlocker extension. await fetch('http://127.0.0.1:8080/hxo.json?dummy=2s21&a ...

Ways to choose tags that do not contain a particular tag within them

I am trying to utilize querySelectorAll to select all i elements that do not contain a font tag. The selector I attempted is: document.querySelectorAll('i > *:not(font)') <i> <font color="008000">Here goes some text</fon ...

Guide on deploying a Next.js React project with IIS on a Windows Server

Our goal is to deploy the application on an IIS server while ensuring it supports dynamic routing. After attempting to install IIS node, we are unsure of our next steps. Do we need to load a specific file like server.js in order to run the application ...

Using Next.js with Firebase emulators

I've been struggling to configure Firebase's V9 emulators with Next.js, but I keep running into the same error message. See it here: https://i.stack.imgur.com/Uhq0A.png The current version of Firebase I'm using is 9.1.1. This is how my Fir ...