Locate a specific item within a JavaScript array using the array.find() method

Searching for an element in a JavaScript array using the find method

 const array = [{
    "key1": "val1",
    "key2": "val2",
    "key3": "val3",
    "key4": "val4",
    "key5": "val5",
},
{
    "key1": "val6",
    "key2": "val7",
    "key3": "val8",
    "key4": "val9",
    "key5": "val10"
}]

We are looking to search for the value searchvalue. It is expected to match with val1, and if it does, we want to retrieve key5:

array.find((element) => element.key1 === searchvalue).key5)

If no matching element.key1 === searchvalue is found, then the search should be based on key2 and key6 of the result:

array.find((element) => element.key2 === searchvalue).key5)

At present, the workflow involves:

var arrayElement = array.find((element) => element.key1 === 
    searchvalue)
const value =  (arrayElement !== undefined ) ? arrayElement.key5: array.find((element) => element.key2 === 
    searchvalue).key6;

Answer №1

To efficiently retrieve a value from an object, you can chain attempts to find the object and access its value.

var array = [{ key1: "val1", key2: "val2", key3: "val3", key4: "val4", key5: "val5" }, { key1: "val6", key2: "val7", key3: "val8", key4: "val9", key5: "val10" }],
    searchvalue = "val7",
    result = 
        (array.find(o => o.key1 === searchvalue) || {}).key5 ||
        (array.find(o => o.key2 === searchvalue) || {}).key4;

console.log(result);

Answer №2

If your data is in the form of an array of objects, you can utilize another iteration method by using .some() to search for a specific value within the object keys.

const array = [
    {"key1": "val1","key2": "val2","key3": "val3","key4": "val4","key5": "val5",},
    {"key1": "val6","key2": "val7","key3": "val8","key4": "val9","key5": "val10",}]

const search = 'val6';
const res = (array.find(i => Object.keys(i).some(k => search === i[k])) || {}).key5
console.log(res)

Answer №3

Iterating through the elements in an array, you can compare each value with a search term. If a match is found, return that specific element; otherwise, return an empty object by default. Afterwards, access key5 on the matched value.

const array = [{"key1": "val1","key2": "val2","key3": "val3","key4": "val4","key5": "val5",},{"key1": "val6","key2": "val7","key3": "val8","key4": "val9","key5": "val10",}]

let find = (arr,searchValue) => (arr.find(v => {
  return Object.values(v).some(value => value === searchValue)
}) || {}).key5

console.log(find(array,'val3'))
console.log(find(array,'no matching value'))

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

Having difficulty transferring images from the frontend to Cloudinary or any backend system

My goal is to upload an image from the frontend to Cloudinary for use as a profile picture in my app. Below is the code I am using: import { StyledInput, StyledLabel} from '../FormInputs/styles' import { useState } from 'react' import { ...

Utilizing JSON with AJAX to dynamically fetch data on a separate webpage results in the page reloading despite implementing the e.preventDefault() method

Looking to retrieve a value on a new page and navigate without refreshing? I'm utilizing the POST method here along with JSON to fetch values. Still learning the ropes of this Ajax code! My goal is to move from the team.php controller page to team_d ...

Utilizing JQuery to Retrieve the Smallest Key in a Dictionary Above a Specified Value

My goal is to identify the smallest value in an array that is greater than a specified input value. var qty = 6; var bulkPricing = [ { max: 5, price: 10.25 }, { max: 1, price: 11.95 }, { max: 15, price: 9.25 }, { max: 35, price: 9.00 }, ...

Unable to modify date or time in react-datetime package

Upon clicking the input box and entering a valid value, the input will either clear or be assigned a random date and time. This feature allows for the selection of a date or time using the mouse. Typing in the input will clear it or assign random values. ...

Updating and adding information in a JSON file using PHP functionality

I have a function to control and update data in a post. However, I am encountering an issue where the function both updates existing information and adds duplicate information during the second addition. Can anyone assist me in identifying where the mista ...

Can a dynamic type assignment be implemented in the C programming language?

I am currently in the process of developing a series of functions in C that will enable a dynamically expanding array. In this particular instance, I have designed a struct containing three key variables: len which keeps track of the current length of the ...

The query callback does not recognize 'done' as a function, leading to a

I'm attempting to save the result of a query into a variable. I've learned that using a callback is necessary for this task. However, I am encountering errors in the process. function fetchUserData(user) { if (user.checkUserStatus) { var u ...

Assigning properties to the constructor using `this.prop`

Within a React class component, I have multiple methods and the component receives various props. I am contemplating whether I should assign each prop as this.propName in the constructor and then access them using this.propName. For your reference, below ...

Modify document on a remote server through a web interface

I am looking to implement a feature on my webpage where users can edit Excel files directly. Here are some considerations I have: Provide links for users to access Excel files and open them in their default program for editing Enable seamless uploading o ...

When Select2 doesn't find a suitable option, the text "other" will be displayed

Is it possible to show a default option in select2 dropdown if the user's typed input does not match any available options? $("something").select2({ formatNoMatches: function(term) { //return a predefined search choice } }); I have searched ...

What is the best way to transform a single quote within an element of an array, which is part of an object, into a double quote without having to generate a new array

I've been advised to use a specific code for one of the problems I tackled some time ago. I'm attempting to figure it out but so far, I haven't made any progress. The challenge is to accomplish this task using replace(), map() and more withi ...

Navigating a mobile-friendly menu anytime!

I'm in the process of creating a responsive "hamburger" menu for mobile devices. The HTML code I have implemented is as follows... .menu_closed { color: red; } .menu_open { color: blue; } <script src="https://ajax.googleapis.com/ajax/libs/jq ...

Utilize NodeJS API to convert a base64 data string into a downloadable PDF file

My NodeJS API is set up to communicate with another API and fetch a data object in the form of a Base64 string. The client making the API call needs to be able to download a PDF file generated from this base64 data. What is the best way to return the dat ...

Can you trigger the playback of a sound file by clicking on a specific URL?

Can a sound file be played when clicking depending on the URL? For example: url/sample/#1 Click to play sound1 url/sample/#3 Click to play sound2 ...

IE11 experiencing delays in loading Google Maps

When I load the attached HTML in Chrome and Mozilla browsers, it renders very quickly. However, in IE11, I encounter several timeout errors, and the map takes 30 seconds to finally render. Despite trying various settings in IE11, I have been unable to res ...

Creating a separate array based on a specific column value

I'm looking to organize data into different arrays based on column values. Here are two sample arrays: First array: Array ( [1] => Products [3] => Services [4] => External [5] => Accessories ) Second array: Array ( ...

Modify the value within vc-date-picker > v-text-field by utilizing v-for

I need the value :value to automatically update from inputValue.start to inputValue.end. This means that when I click on the end date, it should be reflected in the second text field. Similarly, if I select a date range in the second text field, the first ...

Utilizing Vector3 for Parametric Geometry calculations

As I update a script to a newer version of three.js, I encountered an issue with ParametricGeometry. The error message "THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter" keeps appearing. Below is the section of code causing t ...

Tips for extracting values from a JSON object

I have been attempting to retrieve the value from an array without success. Here is the current array: [{0: {value: 2, label: "ARKANSAS"}}] When I try to use JSON.parse(object), I encounter the error VM20617: 1 Uncaught SyntaxError: Unexpected ...

Transformation of Array of Objects to Array of Values using Node.js

I am looking to transform the following: [{ prop1: '100', prop2: false, prop3: null, prop4: 'abc' }, { prop1: '102', prop2: false, prop3: null, prop4: 'def' } ] into this format: [[100,false,null,'abc&ap ...