ID based list conversion
March 22, 2025 ยท AI Conversations
label: cat.snippet.title,
value: cat.id
}));
How to add id based list
### Original Code (List format)
videosCategories.value = response.data.items.map(cat => ({
label: cat.snippet.title,
value: cat.id
}));
This produces an **array** like:
[
{ label: "Music", value: "10" },
{ label: "Gaming", value: "20" }
]
—
### To create an **object based on `id`**, use:
const categoriesById = response.data.items.reduce((acc, cat) => {
acc[cat.id] = {
label: cat.snippet.title,
value: cat.id
};
return acc;
}, {});
This gives you:
{
"10": { label: "Music", value: "10" },
"20": { label: "Gaming", value: "20" }
}
You can assign it to a variable like:
videosCategories.value = categoriesById;
Let me know if you want both formats together (array + id-based object) or need to include more fields.
Hereโs how you can convert the list into an **object keyed by `id`**:
### ๐ Using `reduce` for ID-based list:
const videosCategoriesById = response.data.items.reduce((acc, cat) => {
acc[cat.id] = {
label: cat.snippet.title,
value: cat.id
};
return acc;
}, {});
### ๐ Example:
Given this sample input:
response.data.items = [
{ id: '1', snippet: { title: 'Music' } },
{ id: '2', snippet: { title: 'Sports' } }
];
The output will be:
{
'1': { label: 'Music', value: '1' },
'2': { label: 'Sports', value: '2' }
}
This is useful when you want **fast lookup by ID** rather than iterating through an array every time.
Let me know if you want both versions (array and id-based object) stored together or used with Vue reactivity.
Hereโs how you can do that:
### โ
Scenario:
– You have a list of items from `response.data.items`.
– You have a separate list of **IDs you want to keep**, e.g., `allowedIds`.
– You want to **filter** the items so that only those with matching IDs go into the final array.
### ๐ง Code:
const allowedIds = ['1', '3', '5']; // replace with your actual list of allowed IDs
videosCategories.value = response.data.items
.filter(cat => allowedIds.includes(cat.id))
.map(cat => ({
label: cat.snippet.title,
value: cat.id
}));
### ๐ง What This Does:
– `filter(…)` keeps only the categories whose `id` exists in `allowedIds`.
– `map(…)` then converts them into your desired format.
### ๐ Example:
If your response has:
[
{ id: '1', snippet: { title: 'Music' } },
{ id: '2', snippet: { title: 'News' } },
{ id: '3', snippet: { title: 'Gaming' } }
]
and your `allowedIds` is `['1', '3']`, the result will be:
[
{ label: 'Music', value: '1' },
{ label: 'Gaming', value: '3' }
]
Let me know if `allowedIds` is coming from a dynamic source like another API or computed list โ I can help tailor it.