Best practices for extracting values from an array in JavaScript

I am looking to extract specific values from a MAP in JavaScript based on its id ("codi" within the object).

My array resembles the following but is larger:

0: {codi: '291', literal: 'MEDIFIATC Progres 2010 ', check: true}
1: {codi: '292', literal: 'MEDIFIATC Progres < 2010 ', check: true}
2: {codi: '293', literal: 'MEDIFIATC Progres ', check: true}
3: {codi: '294', literal: 'MEDIFIATC Progres 2013 ', check: true}
4: {codi: '295', literal: 'MEDIFIATC Progres 2014 ', check: true}
5: {codi: '296', literal: 'MEDIFIATC MEDIFIATC ', check: true}
6: {codi: '297', literal: 'MEDIFIATC MEDIFIATC P5 ', check: true}
7: {codi: '298', literal: 'MEDIFIATC MEDIFIATC P15 ', check: true}
8: {codi: '299', literal: 'MEDIFIATC MEDIFIATC DIAGONAL ', check: true}

Currently, I am using a simple loop where I iterate through and return the entry when my variable matches the "codi".

function getSubgroup(codi) {
    for(j = 0; j < Object.keys(subGroupList).length; j++) {
        if (codi == subGroupList[i].codi) {
            return subGroupList[i];
        }
    }   
}

How can I enhance this process?

In addition, I need to extract the values that I will be returning from my primary array. Currently using information from: How can I remove a specific item from an array? , any further assistance on this would be appreciated.

Thank you.

EDIT: I would like to share useful links here provided by Simone Rossaini in the comments:

Answer №1

It would be most efficient to invest in transforming the object into a map with the key as the codi and the value as the actual object. This way, any further extraction can be done in constant time O(1).

var obj = {
  0: {codi: '291', literal: 'MEDIFIATC Progres 2010 ', check: true},
  1: {codi: '292', literal: 'MEDIFIATC Progres < 2010 ', check: true},
  2: {codi: '293', literal: 'MEDIFIATC Progres ', check: true},
  3: {codi: '294', literal: 'MEDIFIATC Progres 2013  ', check: true},
  4: {codi: '295', literal: 'MEDIFIATC Progres 2014 ', check: true},
  5: {codi: '296', literal: 'MEDIFIATC MEDIFIATC  ', check: true},
  6: {codi: '297', literal: 'MEDIFIATC MEDIFIATC P5 ', check: true},
  7: {codi: '298', literal: 'MEDIFIATC MEDIFIATC P15 ', check: true},
  8: {codi: '299', literal: 'MEDIFIATC MEDIFIATC DIAGONAL ', check: true}
}

// converting the object into an array
// disregard if already an array
var arr = Object.values(obj)

var result = arr.reduce(function(agg,item) {
  agg[item.codi] = item;
  return agg;
}, {})

console.log(result);
// now you can:
console.log(result["294"]);

Answer №2

If you're aiming for the best performance, conducting benchmarks is essential. However, keep in mind that optimal results may vary between different browsers and runtime environments.

Consider utilizing newer array methods in JavaScript such as find. It's worth noting that filter might be slower since it continues iterating even after finding a match, searching for additional matches.

item = listOfItems.find(item => item.code === targetCode)

Answer №3

When the unique values of codi are considered, you can transform the array into either a Map or an object using the codi value as the key. This approach simplifies accessing the data.

An older question with various answers discussing the merits of each structure will aid in determining which one to utilize.

Map:

const arr=[{codi:"291",literal:"MEDIFIATC Progres 2010 ",check:!0},{codi:"292",literal:"MEDIFIATC Progres < 2010 ",check:!0},{codi:"293",literal:"MEDIFIATC Progres ",check:!0},{codi:"294",literal:"MEDIFIATC Progres 2013  ",check:!0},{codi:"295",literal:"MEDIFIATC Progres 2014 ",check:!0},{codi:"296",literal:"MEDIFIATC MEDIFIATC  ",check:!0},{codi:"297",literal:"MEDIFIATC MEDIFIATC P5 ",check:!0},{codi:"298",literal:"MEDIFIATC MEDIFIATC P15 ",check:!0},{codi:"299",literal:"MEDIFIATC MEDIFIATC DIAGONAL ",check:!0}];

const map = new Map();

for (const obj of arr) {
  map.set(obj.codi, obj);
}

console.log(map.get('298'));

Object:

const arr=[{codi:"291",literal:"MEDIFIATC Progres 2010 ",check:!0},{codi:"292",literal:"MEDIFIATC Progres < 2010 ",check:!0},{codi:"293",literal:"MEDIFIATC Progres ",check:!0},{codi:"294",literal:"MEDIFIATC Progres 2013  ",check:!0},{codi:"295",literal:"MEDIFIATC Progres 2014 ",check:!0},{codi:"296",literal:"MEDIFIATC MEDIFIATC  ",check:!0},{codi:"297",literal:"MEDIFIATC MEDIFIATC P5 ",check:!0},{codi:"298",literal:"MEDIFIATC MEDIFIATC P15 ",check:!0},{codi:"299",literal:"MEDIFIATC MEDIFIATC DIAGONAL ",check:!0}];

const out = {};

for (const obj of arr) {
  out[obj.codi] = obj;
}

console.log(out['298']);

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

Ways to have Express display a randomly selected question from my personal JSON file

I have set up a personal server to enhance my backend coding skills. Currently, it is in its initial phase. I have developed a basic express application where I can import and display a JSON file. However, I am facing a challenge with automatically loading ...

Setting a cookie within an Angular interceptor

My angular interceptor function includes a request object. intercept(req: HttpRequest<any>, next: HttpHandler) { return next.handle(req); } I am looking to set my token in the request cookie under the name my-token. How can I achieve this? I ...

Converting Nokogiri's Ruby Array of objects into JSON format

I have a collection of anchor tags returned by Nokogiri that I need to transform into a hash of values in order to present them as JSON format. Additionally, I must include some key/value pairs during this process. The ultimate goal is to generate a JSON d ...

divide the information within an HTML table cell

One way I have figured out to populate the cell of a table is by using the following code: {% for row in data %} <td> {{ row[4] }}</td> Now, let's say I have the data "['sugar']:['3642847']:['2020-08-21' ...

Transmit communication from Controller to AJAX script on View page

I am currently utilizing jQuery and AJAX within the View to send data to the Controller for database writing. After a successful submission, a div tag with a green background displaying "OK" text is shown. However, I am interested in implementing a check w ...

Utilizing the SET command to exclude previously logged-in users within a repetitive script

Trying to utilize a set to prevent users from being reprinted in my code. Python accepted the code without any bugs, but when I run it on a 10-second loop, it continues printing users who should have already been logged. My first time using a set and I&apo ...

The specified function for handling NetworkError is currently unavailable

I'm trying to implement a retry mechanism for URL calls in case of network failure using the 'cockatiel' library. Below is the code snippet I have written: import { retry, handleType, ExponentialBackoff} from 'cockatiel'; const ...

Retrieve data from each URL listed in a JSON array using React

My json file structure was as follows: [ { "name": "google", "route": "/google", "url": "www.google.com" }, { "name": "bing", "route": " ...

Filtering JSON attributes

Is there a recommended method for filtering out nested keys in JSON and removing them? Here's an example: { "id" : "1", "key1" : "val1", "key2" : "val2", "name" : "someone", "age" : 39, "data" : [ { "id" : "1234", "key ...

Struggling to remove the image tag from the jQuery ajax response

My web app is designed to send an ajax post request to a PHP script, which then returns a chunk of HTML data. This HTML includes an image and a table of information. The challenge I'm facing is how to extract the image from the rest of the HTML so tha ...

Adding a JSON file to an established row within a DynamoDB table

As a newcomer to AWS and Python, I am looking to upload a JSON file to an existing table row. Currently, my table has a composite primary key, 4 columns of data, and the requirement to add a 5th column by appending a JSON file to a specific item in the tab ...

I seem to be facing a challenge with retrieving results in my app when using mongoose - what could be causing this issue

mongoose.connect('mongodb://localhost:27017/codealong'); When I attempt to connect to MongoDB and post data, the process is successful but I do not receive any results in my browser. Instead, all I see is an empty square bracket [ ]. These are ...

The onLayoutChange function keeps overwriting the data stored in my local storage

When my layout changes, the new changes are saved into local storage and the layout state is updated. onLayoutChange(layouts) { saveToLS("layouts", layouts); } However, an issue arises when the page is refreshed. The layout g ...

Access JSON information from a URL by utilizing Java

I have read some answers like Simplest way to read JSON from a URL in Java but it did not work. Okay, here is my code: package day1; import java.net.HttpURLConnection; import java.net.URL; import java.util.Scanner; import org.json.simple.JSONArray; imp ...

Decoding JSON data in a Webmethod from an AJAX call

I am faced with a challenge regarding passing a JSON object from JavaScript to a VB.Net WebMethod via an ajax request and then attempting to deserialize it. Despite successfully passing the object, I encounter an error during deserialization: Error convert ...

Guide to sorting data by the status value within a JavaScript object?

I have a JavaScript object structured like this: { "3": { "id": 3, "first": "Lisa", "last": "Morgan", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bbd7d6d4c9dcdad5fbdcd6dad2d795d8d4d6">[email&# ...

Implement a custom email template for the contact form utilizing Express and Sendgrid

I have set up a basic contact form that utilizes the Node Sendgrid helper library for sending emails. My goal is to incorporate a template email/contact.jade that will convert to HTML and include the necessary context. I understand that this template shou ...

Ways to automatically assign default select options using an array

When fetching options and values from my database in the form of an array, I aim to have these options/values pre-selected by default in a multiple select list for users to view and update their data as needed. //data stored in the database $mytitle = a ...

Utilize the useState hook to update state when changes occur in the

I currently have a functional component that utilizes a useState hook. The values it holds are sourced from my redux store, and I aim to update the state with the new store state every time an action is dispatched. At the moment, I've manually set an ...

Using a React button to sort through an array

Hey there, I'm currently working on an app that filters a list based on user input. The idea is to click on buttons to exclude users with specific letters in their names. However, the code I have right now isn't functioning properly. Any assistan ...