Currently, I am faced with the challenge of sending data to the server that contains multiple ids with sub ids. I have been utilizing arrays to handle this, but the repetitive use of find() and findIndex() functions in the DOM (specifically with Vue) is starting to become cumbersome. I wonder if there is a more direct way to access ids, allowing me to simply check or retrieve them using something like order[id][subid].
At the moment, my data structure looks like this:
let data = {
orders: [
{ order_id: 4, items: [{ item_id: 6 }, { item_id: 7 }, { item_id: 8 }] },
{ order_id: 1, items: [{ item_id: 1 }, { item_id: 2 }, { item_id: 3 }] },
];
}
For instance, when I need to check if an item within an order is selected, I have to go through the following steps:
function check(order_id, item_id) {
let order_i = data.orders.findIndex((o) => o.order_id == order_id);
if (order_i != -1) {
let item_i = data.orders[order_i].items.findIndex((o) => o.item_id == item_id);
}
if (item_i != -1) {
return true;
} else {
return false;
}
}
I am looking for a more efficient alternative, such as:
let data = {
orders: {
4: {6:'',7:'',8:''},
1: {1:'',2:'',3:''}
}
}
With this structure, I could simply use
data.orders?.[order_id]?.[item_id]
for quick access. However, I am unsure if this is the best approach. Are there any other structures I could use that do not involve arrays?