[Vuejs]-Iterate array of object and save values

1๐Ÿ‘

โœ…

const products = [{family : 'mugs', name :'black mug' , article_id : 1728}, {family : 'tees', name :'red t-shirt' , article_id : 1332 }, {family : 'mugs', name :'tea white mug' , article_id : 2748}, {family : 'tees', name :'green woman t-shirt' , article_id : 1332}];

const grouped_products = products.reduce((acc, {family, article_id}) => {
    const i = acc.findIndex(p => p.family === family);
    if(i !== -1) {
      return [
        ...acc.slice(0, i),
        {...acc[i], article_id: (acc[i].article_id + ',' + article_id)},
        ...acc.slice(i + 1, acc.length)
      ];
    }
    return [...acc, {family, article_id}];
}, []);

console.log(grouped_products);

0๐Ÿ‘

loop on products and use a map where key is family and value is article id.
Then keep adding article ids for a family in the map.

0๐Ÿ‘

let grouped_products = {};

products.forEach(p => {
    grouped_products[p.family] = [...grouped_products[p.family], p.article_id];
})

// to make an array of object by family, as you wish
grouped_products = 
    Object.keys(grouped_products).map(k => { family: k, articles_ids: grouped_products[k] });

0๐Ÿ‘

As @terry said products should be array like :

products = [
    {
        family : 'mugs', name :'black mug' , article_id : 1728 
    }, 
    {
        family : 'tees', name :'red t-shirt' , article_id : 1332 
    }, 
    {
        family : 'mugs', name :'tea white mug' , article_id : 2748 
    }, 
    {
        family : 'tees', name :'green woman t-shirt' , article_id : 1332 
    }
];

Now, to get desired output you can do this :

let group= products.reduce((prev, curr) => {
   let i = prev.findIndex(item => item.family === curr.family);

   if(i > -1){
       prev[i].article_ids.push(curr.article_id);
   }else{
       prev.push({
           family: curr.family, 
           article_ids: [curr.article_id]
       });
    }
    return prev;
},[]);

0๐Ÿ‘

let products = [
    {
      family : 'mugs', name :'black mug' , article_id : 1728 
    },
    {
      family : 'tees', name :'red t-shirt' , article_id : 1332 
    },
    {
      family : 'mugs', name :'tea white mug' , article_id : 2748 
    },
    {
      family : 'tees', name :'green woman t-shirt' , article_id : 1332 
    }
]

function insertItem(accum,val){
    accum[val.family] = accum[val.family] ?  accum[val.family] + "," +  val.article_id : val.article_id ;
    return accum;
}

let mapped = products.reduce(insertItem,{});
let grouped = [];
Object.keys(mapped).map((key)=> grouped.push({"family":key, "article_ids":mapped[key]}))

First Iโ€™m just grouping everything by family using an object as an associative array

Then Iโ€™m using a conditional assignment with the ? to append the value with a preceeding comma if there is one

Iโ€™m not sure if you actually wanted comma seperated values or an array for the article_ids but if you wanted commas, this should work

Leave a comment