Discover a corresponding object within an array

I am currently dealing with an array of objects in Javascript where I need to verify if a certain value exists within any object and return the corresponding id. The issue arises when using the some() function as it only seems to match the first object.

The array in question is structured as follows:

const testObj = [
  {id: 1, nombre: "Juan"},
  {id: 2, nombre: "María"},
  {id: 3, nombre: "Pedro"}
];

This is my current approach:

let test = 'María'

let priority;

testObj.some(item => item.nombre === test ? priority = item.id : priority = 7)

However, upon checking the result, it yields:

console.log(priority) // 7

I'm puzzled as to why it fails to return the accurate id when the specified value does exist within one of the objects. Any insights on this behavior?

Answer №1

The method Array.some() will stop as soon as the callback function returns a truthy value, such as true. In this case, the some ends when the priortiy is set to 7 due to its truthy nature. The purpose of Array.some() is to determine if at least one item meets certain criteria, with the result being a Boolean value (true if at least one matches, false if none). It's not intended for simple looping or finding a specific item.

Instead, consider using Array.find(). If the item is located, destructure its id and assign it to priority. When Array.find() fails to find an item, it will return null. To address this scenario, utilize the Nullish coalescing operator (??) to provide a fallback object with a default value of 7.

const testObj = [
  {id: 1, nombre: "Juan"},
  {id: 2, nombre: "María"},
  {id: 3, nombre: "Pedro"}
];

const test = 'María'

// utilizing destructuring
const { id: priority } = testObj.find(o => o.nombre === test) ?? { id: 7 }
console.log(priority)

// using a ternary operation
const item = testObj.find(o => o.nombre === test)
const priority2 = item ? item.id : 7
console.log(priority2)

// employing optional chaining
const priority3 = testObj.find(o => o.nombre === test)?.id ?? 7;
console.log(priority3)

Answer №2

The Challenge

An issue arises when you set the priority value to 7 in the else condition of the ternary operator, as it will always execute regardless of whether the value is found or not.

The Resolution:

To address this, adjust your code so that the priority value is only set when the desired value is found within the array.

let test = 'María';
let priority = null;
const testObj = [ {id: 1, nombre: "Juan"}, {id: 2, nombre: "María"}, {id: 3, nombre: "Pedro"} ];

testObj.some(item => {
  if (item.nombre === test) {
    priority = item.id;
    return true;
  }
});

console.log(priority); // 2

Utilizing for..of Loop:

let test = 'María';
let priority = 7;

for (const item of testObj) {
  if (item.nombre === test) {
    priority = item.id;
    break;
  }
}

console.log(priority); // 2

Implementing find() Method:

let test = 'María';
let priority = testObj.find(item => item.nombre === test)?.id || 7;

console.log(priority); // 2

Note : Utilizing find() or a straightforward for..of loop with an early break statement may be more effective than using some.

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

Turning off and on CSS transitions to set the initial position

Is there a way in javascript to position divs with rotations without using transitions initially for an animation that will be triggered later by css transition? I have tried a codepen example which unfortunately does not work on the platform but works fin ...

Is there a way to customize the Webpack output to incorporate specific options solely for a particular bundle?

Currently, I am using Webpack 4 to build multiple bundles. My requirement is to add the output options libraryTarget and library for a single bundle only. The default configuration looks like this: output: { path: path.resolve(__dirname, 'dist/j ...

What is the most effective way to send multiple values through the <option> value attribute?

Currently, I am in the process of creating an online shopping item page. To display all the necessary information about an item (such as price, image, name, etc.), I use the 'item_id' to loop through a database containing item info. Additionall ...

Mastering the art of jQuery scrolling: A step-by-step guide

Is there a way to utilize jQuery for scrolling purposes? For example, transforming this: <ul class="nav navbar-nav navbar-right"> <li class="active"><a href="#home">Home <span class="sr-only">(current)</span></a> ...

Typescript: organizing nested types within an interface

My goal is to create an interface CountersData based on my JSON data. The challenge lies in the nested id property, which contains an array of nested dictionaries. I want this property to be optional. However, I have not been successful in making it option ...

Obtain the corresponding element from the selectors utilized in the jquery.is function

$("#see1, #seeAlso1, .see").is(':checked') This code snippet will give you a boolean result. Are you looking for a way to retrieve the first element that matches and returns 'true'? ...

"Exploring the Latest Features of NextJS 13: Enhancing Server

Currently, I am in the process of familiarizing myself with NextJS 13 and its new APP folder structure. I am facing a challenge in updating data on server components without needing to reload the page or the app. My HomePage server component fetches a list ...

Retrieve the result set rows and store them in an array as individual objects

I'm attempting to fetch data from a MySQL database using Angular and PHP. My Angular code looks like this: $http({ url: "http://domain.com/script.php", method: "POST", headers: {'Content-Type': 'applica ...

What is the best way to retrieve the value of the nearest text input using JavaScript?

I am currently working on designing an HTML table that includes a time picker in one column for the start time and another time picker in a separate column for the end time within the same row. My goal is to retrieve both values (start time and end time), ...

Creating an HTML element within a three.js globe

I have a globe created using three.js Reference: I am trying to display an HTML div at a specific latitude/longitude on the globe. Can someone guide me on how to position the div at a particular lat/long? What I've attempted: I'm currently stu ...

Vue.js - Maintaining input value when model declines updates

I am working on a text input that allows users to enter numbers with a maximum of three digits after the decimal point: <v-text-field type="text" :value="num" @change="changeNum($event)" /> <p>{{ num }}</p> ... export default { data: ...

What is the process for retrieving wallet transactions using Alchemy websockets?

I am trying to retrieve all new transactions from a specific wallet using the code provided. However, I am encountering an issue when using the function tx["transaction"]["from"] to filter transactions based on the specified wallet. I am utilizing Alchemy ...

Teaching jQuery selectors to detect recently-added HTML elements

Unable to find a solution in the jQuery documentation, I am seeking help here for my specific issue. Embracing the DRY principle, I aim to utilize JavaScript to include a character countdown helper to any textarea element with maxlength and aria-described ...

Are there any userscripts available for interactive websites?

I frequently create small GreaseMonkey UserScripts for my personal use. However, I often struggle with a recurring issue: How can I adapt to the changing nature of websites? For example, popular webstores like Amazon now update content dynamically withou ...

Identifying Inaccurate Device Date Using JavaScript

Is there a way to detect if the device's date is inaccurate using javascript? (For example, displaying an alert if the current date is 2016/6/16 but the device date is 2016/6/15) ...

I encountered a "Bad Request" error when trying to login through my nodejs server, and I'm unsure of the reason behind this issue. As a beginner in nodejs, I'm still learning the ins and

passport.use(new LocalStrategy(async(email,password,done) => {    try{     const user = await User.findOne({email:email})     if(!user){        return done(null,false,{message:"Invalid email"})     }     const isValidPassword =aw ...

What purpose does the additional symbol "$()" serve in the selector "$($())"?

Currently, I am looking to incorporate a jQuery scrollspy feature into one of my ongoing projects. Upon coming across this jsfiddle (https://jsfiddle.net/mekwall/up4nu/), I successfully integrated it into my project. However, I have hit a roadblock while ...

The raycaster is experiencing issues when used with multiple cameras in the Three.js library

I am currently developing an application similar to the threeJs editor. In this project, I have implemented four different cameras, each with unique names and positions. Here is an example of one of the cameras: cameras['home'] = new THREE.Combi ...

Using jQuery, selectively reveal and conceal multiple tbody groups by first concealing them, then revealing them based on

My goal is to initially display only the first tbody on page load, followed by showing the remaining tbody sections based on a selection in a dropdown using jQuery. Please see below for a snippet of the code. //custom JS to add $("#choice").change(func ...

Tips on extracting specific information from nested JSON objects

I have a packet with the following data and I need to extract a specific part: "data":"YOeNkAAg1wQAYjm/pg== Is there a way to achieve this using JavaScript in node-red? { "payload": "lora/01-01-01-01-01-01-01-01/39-31-37-33-5b-37-67-19/packet_sent { ...