简体   繁体   中英

How to get all the 'items' data from this list?

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));

安慰

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"]

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.

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