Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I want to collect all the particular object from nested object array object

I want to collect all the object of a particular category from the nested array-object data in to one single array

let categoriesxy= [
        {
            catid: 'category-1',
            product: [
                {
                    id : 1,
                    name: 'sparrow'
                },
                {
                    id : 2,
                    name: 'parrot',
                }
            ]

        },
        {
            catid: 'category-2',
            product: [
                {
                    id : 1,
                    name: 'elephant',
                },
                {
                    id : 2,
                    name: 'horse',
                },
                {
                    id : 3,
                    name: 'lion',
                },
                {
                    id : 4,
                    name: 'tiger',
                }
            ]
        },
    ];

i want to store data inside product in to one array like xys = [ { id , name }, { id , name }… so on ]
so i can call it like xyz.id, xyz.name etc

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you wish to also keep the category for each product you can do it like:

const categoriesxy = [ /* your list */ ]

const products = []
categoriesxy.forEach((category) => {
  category.product.forEach((product) => {
    products.push({ ...product, catid: category.catid })
  }
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading