0

I have my data in below:

  fakeData = [
        {
            "option_name" : 'optionA',
            "display_line_num" : 1
      },
        {
            "option_name" : 'optionB',
            "display_line_num" : 2
      },
        {
            "option_name" : 'optionC',
            "display_line_num" : 2
      },
        {
            "option_name" : 'optionD',
            "display_line_num" : 3
      },
        {
            "option_name" : 'optionE',
            "display_line_num" : 4
      },
        {
            "option_name" : 'optionF',
            "display_line_num" : 4
      }
    ];

and I am trying to make my html look like desired look

The display_line_num represent which row the element should be placed. I am pretty lost on how to approach to this.

my try here I tried to create a hashmap where key is the line number, and value is how many options are in that line number. However, I am still lost. I am stuck for a long time, and I wonder what are some good ways to approach this?

I know that we may need to use *ngFor, for example , <li *ngFor="let item of items;"> ....

but there will be a nested for loop which one row can have several options, and sometimes a row only has a option. How can I handle these circumstances?

Can someone give me a hint? Thank you!

zhinee
  • 105
  • 1
  • 10
  • Try this link https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-an-array-of-objects, it might have something that can help your problem. – rdr20 Feb 22 '21 at 06:57

1 Answers1

0

I have updated your mapDatas function:

mapDatas( data: any ){

  const dataObj:any = {}

  this.fakeData.forEach(data => {
    const {display_line_num: key, option_name: value} = data;
    dataObj[key] = dataObj[key] ? [...dataObj[key], value] : [value]
  });

  return Object.values(dataObj);

}

Here we are iterating through the fakeData array and pushing each item's option_name value in a nested array and the index of each array is the display_line_num of each item. So, when more than one element have the same display_line_num, they will be put in the same array. And finally, we are returning the object converted to an array. Now you can iterate through each item using ngFor in your template.

Shuvo
  • 1,253
  • 9
  • 18