change lodash groupby key for undefined change lodash groupby key for undefined vue.js vue.js

change lodash groupby key for undefined


This will do

 const groupData = _.groupBy(itemData, item => {   return _.get(item, 'category__article.name', 'no_category'); });

Using _.get to fetch nested value (item.category__article.name) and give default value (no_category) if the value is undefined.

_.get Documentation

const itemData = { 0: {      name: 'article 1',      category_id : 1,      category__article: {        id: 1,        name: 'news'      }    }, 1: {      name: 'article 2',      category_id : 2,      category__article: {        id: 2,        name: 'lifestyle'      }    }, 2: {      name: 'article 3',      category_id : '',      category__article: undefined    }}const groupData = _.groupBy(itemData, item => _.get(item, 'category__article.name', 'no_category'));console.log('groupData', groupData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>


Lodash groupBy method can accept a function as a parameter. So you can default the category value to 'other' as easy as this:

const itemData = {  0: {    name: "article 1",    category: "news"  },  1: {    name: "article 2",    category: undefined  },  2: {    name: "article 3",    category: null  }};const groupkey = "category";const defaultCategory = "other";var value = _.groupBy(itemData, item => {  const value = item[groupkey];  if (!value) {    return defaultCategory;  }  return value;});/*Returns: {  news: [{ name: "article 1", category: "news" }],  other: [    { name: "article 2", category: undefined },    { name: "article 3", category: null }  ]}*/