What is the quickest method to retrieve a specific value from an object within an array in JavaScript?

Today I encountered a problem that made me realize I needed to find a better solution.

The issue at hand involves an immutable array of objects.

[
  {
   id: 0,
   value:10
  },
  {
   id: 1,
   value:20
  },
  {
   id: 2,
   value:20
  },
]

I had the task of searching through this array, locating the object with my specific id, and then retrieving a single value from within that object.

This is how I tackled it:

// extract the entire object from the array
const tempObject = immutableArray.toJS().find(elem => (elem.id === myId));

// create a temporary variable to hold the desired value
let tempValue = 0;

// validate the object
if(tempObject !-- undefined){
   // store the extracted value
   tempValue = tempObject.value;
}

To me, this method seems quite inefficient. Why save the complete object when all I need is one value?

I believe it should be something more streamlined like

const myValue = immutableArray.toJS().find(elem => (elem.id === myId).value);

or even

const myValue = immutableArray.toJS().find(elem => (elem.id === myId)).value;

However, as it turns out, those approaches do not actually work.

Is there a more direct way to access this value without storing the entire object?

Answer №1

b = [{id: 5, value:50}, {id: 6, value:60}, {id: 7, value:70}];
console.log((b.find(e => e.id == 6) || {value: 0}).value); // 60
console.log((b.find(e => e.id == 8) || {value: 0}).value); // 0

Answer №2

let updatedValue = 0;
const searchResult = originalArray.getValues().find(obj => (obj.key == myKey));

if (searchResult) {
   updatedValue = searchResult.val;
}

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

The value of this.$refs.<refField> in Vue.js with TypeScript is not defined

During the process of converting my VueJs project to TypeScript, I encountered an error related to TypeScript. This issue arises from a component with a custom v-model implementation. In the HTML, there is an input field with a 'plate' ref that ...

The Algolia Hit Component is having difficulty functioning properly within a grid layout

I am in the process of converting my next API to an Algolia search. The Hit component is a single component that renders for each record. However, I am facing an issue with implementing a grid layout. Below is the code snippet from before (which was workin ...

Aurelia encountering an error when attempting to load Bootstrap v4 during runtime

In my aurelia.json file, I have the following configuration for bundling vendor scripts. It was directly copied from a working reference implementation and has been functioning properly. { 'build': { 'bundles': [ 'name ...

A step-by-step guide on dynamically utilizing ng-outlet in AngularJS

For the past couple of days, I have been immersed in developing an AngularJS app. After two days of brainstorming, I have finally grasped how to utilize AngularJS's new router with components and ng-outlet feature. However, just when I thought everyt ...

Ways to merge two arrays into one in React JS

Here are two arrays presented below: const arrayA = { 0: { id: XXXXXXX, name: "test" }, 1: { id: YYYYYYY, name: "example" } } const arrayB = { 0: { id: XXXXXXX, category: "sea", } 1: { id: YYYYY ...

Is it possible to utilize getServerSideProps with a functional component in Next.js?

Is it feasible to execute the server side props within a component in NextJS? From my understanding, getServerSideProps fetches the data upon entering the page, but is it achievable for it to run during the rendering of a component? The scenario I have is ...

Calculate the total sum of input values using jQuery

Here is the HTML I've been working with: I am trying to create a script where one textbox will display the total amount, and another textbox will display the following data: "name": [{ "id": 3, "qty": 2 }, { "id": 4, "qty": 5 }] Here's ...

Next JS restricts XLSX to return only 100 objects as an array of arrays

I've developed a file upload system that reads Excel files and uploads data to a database (using Mongoose). After implementing the code, I noticed that when I use console.log(sheetData), it returns an array of arrays with objects inside. Each internal ...

Executing Selenium tests: utilizing the webdriver.wait function to repeatedly call a promise

Currently, I am using Selenium ChromeDriver, Node.js, and Mocha for testing purposes... I am facing a dilemma at the moment: The driver.wait function seamlessly integrates with until. I have a promise, which we'll refer to as promiseA. This pro ...

When a user scrolls over an element with a data-attribute,

Looking to create a dynamic header effect on scroll? I have two headers, menu1 by default and menu2 hidden with display:none. In specific sections of my website, I've added a special attribute (data-ix="change-header") to trigger the header change. T ...

What is the best way to invoke a new webpage while also incorporating the data from a form variable?

I am looking to create a link that directs to a new page in the following format: /topic/create&qty=4 Currently, I have the value (which is the number 4) stored in an input field within a form. Initially, I attempted to include everything in the form ...

PHP condition that checks if a variable equals a specific value

$my_zip = $user->zip; $zipstring = $rows['zip_code_pool']; if ( $zipstring == $my_zip ) { echo "in the area!<br />"; } This particular code snippet has a flaw. When using echo $zipstring, it displays values like: 90000,90 ...

Using Array.prototype.map in conjunction with parseInt functions

Recently, I encountered something quite unusual. I am attempting to separate a string containing a time (e.g. "12:00", "13:30") into two distinct integers. I experimented with the following approach: timeString = "12:00" [hours, minutes] = timeString.spl ...

JavaScript classList.remove function experiencing inconsistencies

Take a look at this fiddle: JSFiddle The HTML code: <table class="myTable"> <tr> <th>Some text</th> <td class="align"> <span class=" someStyle">1</span>/<span class="otherStyle">15</span& ...

Angular 4: Issue with Radiobutton values vanishing when another Radiobutton is selected

I have 3 radio buttons that are used to sort different data from an API. However, when I press one radio button, the value of the selected button disappears if another radio button is clicked. This issue can be seen in the screenshots here: https://i.sstat ...

Is there a way to access a JSON node dynamically without relying on the eval function?

Path variables can be unpredictable, ranging from just a to a/b, and even a/b/c. My goal is to dynamically reach a node based on the path provided. The code snippet below achieves this, but I am open to exploring alternative methods that do not involve usi ...

What is the best way to create a mirrored effect for either a card or text using CSS

Can anyone assist me with this CSS issue? When I hover over to view the movie details, the entire word flips along with it. Is there a way to make only the word flip initially, and then have it return to normal when hovered? The HTML code is included belo ...

"Updating a field within a sub-array document in MongoDB: A step-by-step guide

Considering a database containing the following documents: { "_id" : ObjectId("5448f241e47010336375bb21"), "lid" : "Ridali", "items" : [ { "product" : "dogfood", ...

The function batchWriteItem() has been known to produce unpredictable outcomes

Currently in my Node.js project, I am attempting to write records to a DynamoDB table using the batchWriteItem() method. When I call the insertTransactionDetails() function for the first time, I send 9 records to be inserted. On the second call to the sam ...

Track the number of button clicks on the website without ever resetting the count

Hello there! I have a fun idea for my website - it will have a button that, when clicked 5 times, displays the number 5. Even if you refresh the page or load it again, it should still show 5 and allow you to keep clicking. I can create a counter for one ...