Underscorejs - Group objects by property and print them

I have this array:

var ty = [
    {
      "Language": "en-GB",
      "Section": "Sales",
      "ItemName": "Type",
      "Texts": "Having selected the account heading select the calculation ..."
    }, 
    {
      "Language": "en-GB",
      "Section": "Sales",
      "ItemName": "Try",
      "Texts": "This is not happenning tho ..."
    },
    {
      "Language": "en-GB",
      "Section": "Taxes",
      "ItemName": "Save",
      "Texts": "The Master Tax Table has been pre populated with the current UK, ..."
    }];

and i need to group it in a way that according to the section it will contain all the properties that have the same section, like this:

[
    {section: 'Sales', ItemName: ['Type', 'Try'] Texts: ["Having selected the account heading select the calculation ...", "This is not happenning tho."]},

    {section: 'Taxes', ItemName: ['Type'] Texts: ['Having selected the account heading select the calculation.']}
]

So When I print it it will print just the text of each section.

This is the code I have so far:

var log = function(contents) {
  if (_.isArray(contents)) {
    _.each(contents, function(e, i, l) {
      log(e);
      $('#result');
      $('#result').append('</br></br>');
    });
  } else {
    console.log(contents);
    $('#result').append(contents);
  }
};

var ty = [
{
  "Language": "en-GB",
  "Section": "Sales",
  "ItemName": "Type",
  "Texts": "Having selected the account heading select the calculation ..."
}, 
{
  "Language": "en-GB",
  "Section": "Sales",
  "ItemName": "Try",
  "Texts": "This is not happenning tho ..."
},
{
  "Language": "en-GB",
  "Section": "Taxes",
  "ItemName": "Save",
  "Texts": "The Master Tax Table has been pre populated with the current UK, ..."
}];
var out = [];
_.groupBy(ty.Section, function(item){
	section: item.Section
	_.each(ty, function(item) {
  	var hold = {};
  	hold.options = {};
  	hold.options.section[item.ItemName] = {
    	text: item.Texts,
   	};
  	out.push(hold)
	});
});
log(out);

I have tried:

//More code above
_.each(ty, function(item) {
    iName: item.itemName;
  	var hold = {};
  	hold.options = {};
  	hold.options.section.iName = {
    	text: item.Texts,
   	};
  	out.push(hold)

but still it won’t print anything. in my dev tools it doesn’t show anything.

any tips?

Hey @georgereplay,

Something like this should do the trick:

const result = _
  .chain(ty)
  .groupBy('Section')
  .map(function(value, key) {
      return {
          section: key,
          ItemName: _.pluck(value, 'ItemName'),
          Texts: _.pluck(value, 'Texts')
      }
  })
  .value();

adapted from this code.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.