Finding the indexes in JavaScript of the selected array of object IDs

Today, I'm facing the challenge of retrieving JavaScript index based on a specific data ID that I have selected.

I am referring to the documentation at , where they suggest using something like: checkedRows: [data[1], data[3]] to mark a particular row in a table as checked.

My goal is to mark the rows in the table according to the response received from my web API.

Here is a snippet of the sample response data:

response.data.checkedRows // contains [{id: 1234}, {id: 83412}]

Additionally, here is an excerpt of the sample data from the table:

const data = [{
    id: 1234,
    name: 'Jojo'
},{
    id: 43221,
    name: 'Jeff'
},{
    id: 83412,
    name: 'Kacey'
}]

Essentially, I need a dynamic solution similar to this: checkedRows: [data[0], data[2]] as it aligns with the IDs present in response.data.checkedRows.

Thus far, I have attempted to utilize the forEach method:

let selectedIndex = [];
response.data.checkedRows.forEach((d) => {
     this.data.forEach((e) => {
         if (d.id=== e.id) {
             // aiming for a dynamic outcome based on the response.data.checkedRows
             this.checkedRows = [data[0], data[2]]
         }
     });
});

I am currently stuck as I cannot determine how to match the selected indexes with the checkedRows from the response. Any insights would be greatly appreciated!

Answer №1

Utilize the response checkedRows, and then use the callback function to .find the corresponding object in the array:

const checkedRows = [{id: 1234}, {id: 83412}];

const data = [{
    id: 1234,
    name: 'Jojo'
},{
    id: 43221,
    name: 'Jeff'
},{
    id: 83412,
    name: 'Kacey'
}];

const objs = checkedRows.map(({ id }) => (
  data.find(obj => obj.id === id)
));
console.log(objs);

If dealing with numerous elements, consider using a Set of IDs for a more efficient search process and reduced computational complexity:

const checkedRows = [{id: 1234}, {id: 83412}];

const data = [{
    id: 1234,
    name: 'Jojo'
},{
    id: 43221,
    name: 'Jeff'
},{
    id: 83412,
    name: 'Kacey'
}];

const ids = new Set(checkedRows.map(({ id }) => id));
const objs = data.filter(obj => ids.has(obj.id));
console.log(objs);

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

Firefox triggers VideoJS event 'ended' at the beginning

When I use video JS, the "ended" event in Firefox is triggered both at the end and beginning of the video playback. Check out this example in FF: http://jsfiddle.net/planadecu/a3Chu/ All other browsers seem to work fine with this. The code snippet calle ...

Guide to transforming Excel formulas into JavaScript

In my Excel sheet, I have the following formula: =IF($F6=0,"",IF(I6=0,"",$F6/I6)) where F6=7000 and I6 is empty. The Excel result is displaying no data for the formula. Now, I need to convert this formula into JavaScript. function AB6(F6) { var ...

Trouble initializing jSignature on multiple pages with jQuery Mobile

My jquery mobile app is displaying 3 jsignature divs correctly on certain pages, but not on others. The problem arises when the div shows up with a squished height and is unresponsive to touch: Currently, I'm loading these divs using a document ready ...

"By clicking on it, change the href attribute to a new source

I'm currently working on a project that involves swapping thumbnail images to a larger image when the thumbnail is selected. It's functioning as expected, but now I want to allow end users to click on the larger image to display it in jquery.ligh ...

(Definition) What is the proper way to reference a variable inside another variable?

Currently, my project is using inconsistent terminology when referring to variables, and I need to clarify this issue. Let's take an object defined in this way: var anObject = { a: { value1: 1337, value2: 69, value3: "420 ...

Discovering the value of an item when the editItem function is triggered in jsGrid

Within my jsGrid setup, I have invoked the editItem function in this manner: editItem: function(item) { var $row = this.rowByItem(item); if ($row.length) { console.log('$row: '+JSON ...

What is the best way to ensure there is only one instance of a React component visible at any given time?

In my current project with React, I am working on implementing a specific functionality. The challenge I am facing involves three components: ComponentA, ComponentB, and ComponentC. The twist is that ComponentC can be rendered as a child of either Compone ...

Using Javascript to dynamically populate a dropdown menu in Codeigniter's form helper

In my JavaScript code, I have a loop where I create dropdowns by calling a div that contains my CodeIgniter form helper dropdown. Here's an example: for(){ var demo = $('<select>').attr('name','id_'+i).html($(&apos ...

How can a loading bar be shown while a PHP page is loading?

I currently have an HTML form that directs to a PHP file upon submission. The PHP file takes some time to load due to background processes running, so I am interested in implementing a progress bar or alert to indicate when the file is fully loaded. Does ...

Replacing jQuery.ajax from a different directory/domain - problem with using relative URLs

We are incorporating scripts from various sources and domains, including one that contains the definition for jQuery.ajax function. Calls to jQuery.ajax are being made from different places and domains using relative URLs, such as jQuery.ajax("my/relativ ...

Exploring event propagation in React components

Can event bubbling be tested in React? For instance: Class Foo extends React.Component { doSomething() { console.log('bubble'); } render() { return ( <div onClick={this.doSomething}> ...

JavaScript appends a backslash character to a CSS class

I am attempting to populate index.html with the contents from an array using a JavaScript loop. However, I am encountering an issue where a CSS class for picture formatting is displaying some odd characters when rendered in the latest version of Firefox. ...

Assign the serialized form data retrieved via Ajax to a JSON object

Below is the HTML form I have created: <form role="form" id="booking" class="form-horizontal" action="booking.json" method="POST"> <div class="form-group"> <label for="destination">Destination:</lab ...

Ways to identify whether a div is in view and includes an input field

This is a unique question that is not related to the issue of querySelectorAll detecting value in input. Instead of asking whether an input field has a value, I am interested in how to detect if the current visible div contains an input field. This is a n ...

Stop users from being able to input line breaks by pasting

I am currently facing a challenge with my code. Within the code, I have included a textarea where users can input the title of an article, and I want this title to be restricted to only one line. To achieve this, I created a script that prevents users from ...

Issue with BulkInsert: NullPointerException when trying to insert ContentValues array

I am encountering a nullPointerException when attempting to use bulkInsert. The ContentValues appear to be correct, but I suspect there may be an issue with converting them into an array of CV's. if (contactList != null && !contactList.isEmpt ...

In the programming language C, creating a 32-bit pointer for an 8-bit array

In my buffer, each entry is 8 bits in size: uint8_t Buffer[10] = {0x12,0x34,0x56,0x78,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6}; My goal is to create pointers to that array, such as 16 bit and 32 bit pointers. For example: uint32_t *x; x = Buffer; uint32_t *y; y ...

Failed to access the 'totalQty' property as it is undefined

I have developed a cart object that can hold products in a shopping cart. The issue arises when an item is undefined before it gets added to the cart. How can I ensure that the cart is defined even when it's empty during the session? I am using ejs. ...

How can mongoose be used to modify user information in a database?

Hey there, I'm currently working on a personal project and came across an issue. I've successfully set up my (steam) user data to save in mongodb through mongoose. Right now, I have it set to only save a new user if they are not already in the da ...

Can Vue2-Google-Maps dynamically load API keys using props?

Is there a way to access the component props before it gets rendered? I want to dynamically load the Google Maps API based on a passed prop value. import * as VueGoogleMaps from 'vue2-google-maps'; import GmapCluster from 'vue2-google-maps/ ...