简体   繁体   中英

JavaScript Get Indexes based from the Selected Array of Object Id

Today, I'm trying to get the list of javascript index based from the selected data id that I have.

I'm following this guide from https://buefy.org/documentation/table/#checkable where it needs something like this: checkedRows: [data[1], data[3]] to able to check the specific row in the table.

What I need to do is to check the table based from my web API response.

I have this sample response data.

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

and I have the sample data from the table.

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

So basically, I need to have something, dynamically, like this: checkedRows: [data[0], data[2]] because it matches the data from the response.data.checkedRows

So far, I tried using forEach

let selectedIndex = [];
response.data.checkedRows.forEach((d) => {
     this.data.forEach((e) => {
         if (d.id=== e.id) {
             // need the result to be dynamic depending on the response.data.checkedRows
             this.checkedRows = [data[0], data[2]]
         }
     });
});

I'm stuck here because I'm not sure how can I get the index that matches the selected checkedRows from response. Any help?

Map the response checkedRows , and in the callback, .find the matching 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 there are a lot of elements, you can use a Set of the IDs to find instead to decrease the 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM