I have a list of data like below:
The data consist of 6 categories (bags, shoes, girls, bags, and boys) and all of them store the same data (id, items(array: desc, id, imageUrl, name, price), routeName, title).
Now, I want to loop through all categories and just retrieve their name from the 'items', how can I do this?
I have tried the code below and I just can retrieve the name from one of the categories. Are there any ways to get all of the names from all collections? Thanks for helping me.
const { bags, shoes, girls, bags, boys } = collections;
const {items} = bags;
console.log(items.map(item => item.name));
CodePudding user response:
I used this sample data object which mapping with your example. using below array functions can get the result more efficiently.
const data = {
bags: {
id: 1,
items: [
{ desc: "abc", id: 1, imageUrl: "url", name: "Rabbit Crossbody", price:"$10" },
{ desc: "qwe", id: 2, imageUrl: "url", name: "Cat Crossbody", price:"$10" },
{ desc: "pqr", id: 3, imageUrl: "url", name: "Parrot Crossbody", price:"$10" },
],
routeName:"bags",
title:"Bags"
},
boys: {
id: 1,
items: [
{ desc: "abc", id: 1, imageUrl: "url", name: "Lion Crossbody", price:"$10" },
{ desc: "qwe", id: 2, imageUrl: "url", name: "Dog Crossbody", price:"$10" },
{ desc: "pqr", id: 3, imageUrl: "url", name: "Crow Crossbody", price:"$10" },
],
routeName:"boys",
title:"Boys"
},
girls: {
id: 1,
items: [
{ desc: "abc", id: 1, imageUrl: "url", name: "Pig Crossbody", price:"$10" },
{ desc: "qwe", id: 2, imageUrl: "url", name: "Hen Crossbody", price:"$10" },
{ desc: "pqr", id: 3, imageUrl: "url", name: "fish Crossbody", price:"$10" },
],
routeName:"girls",
title:"Girls"
}};
const categories = Object.keys(data); // extract categories
const filteredNames = categories.map(category => {
const items = data[category].items; // extract items of each category
return items.map(item => item.name); // extract names of items into new[]
});
console.log('names', filteredNames.flat());
// ["Rabbit Crossbody", "Cat Crossbody", "Parrot Crossbody", "Lion Crossbody", "Dog Crossbody", "Crow Crossbody", "Pig Crossbody", "Hen Crossbody", "fish Crossbody"]
CodePudding user response:
Try 2 loops:
const allNames = [];
for (const collection of Object.values(collections)) {
for(const item of collection.items) {
allNames.push(item.name);
}
}
console.log(allNames);
It's possible to do this with array functions too, but a loop is often the most obvious.