【问题标题】:Sort array and group it with specific value [closed]对数组进行排序并将其分组为特定值[关闭]
【发布时间】:2020-11-07 12:02:30
【问题描述】:

我有一个包含很多值的数组,如下所示:

我正在尝试通过对具有相同 part_image 值的每个“部分”进行分组来对数组进行排序,然后渲染该值仅链接到 1 次的图像。

我尝试使用 groupBy 函数但没有成功,有人有办法吗?

数组变量:selectedDiam

Component.ts

  ngOnChanges() {
    this.filterDrop();
    console.log(this.selectedDiam, ' SELECTED DIAM');
  }

  filterDrop() {
    this.dataDiam1 = this.dataDynParts;
    let dynDiam1 = this.dataDiam1.map(obj => obj.diam[0]);
    dynDiam1 = dynDiam1.filter((v, i) => dynDiam1.indexOf(v) === i);
    this.dataDiam1 = dynDiam1;


    this.dataDiam2 = this.dataDynParts;
    let dynDiam2 = this.dataDiam2.map(obj => obj.diam[1]);
    dynDiam2 = dynDiam2.filter((v, i) => dynDiam2.indexOf(v) === i);
    this.dataDiam2 = dynDiam2;


    this.createForm();
    this.filteredWithDiam = this.dataDynParts;
    this.selectedDiam = this.dataDynParts;
    this.quotationIdNumber = this.quotationId;
  }

Component.html

<div class="products">
  <div class="d-flex flex-row linesColor ml-2" *ngFor="let products of selectedDiam; let  i = index;">
    <a class="flex1">HERE IS WHERE THE PHOTO SHOULD BE RENDERED</a>
    <a class="flex1">{{products.l3_label}}</a>
    <a class="flex1">{{products.diam[0]}}</a>
    <a class="flex1">{{products.diam[1]}}</a>
    <a class="flex1">
      <input class="number" ngModel="{{products.longueur}}"  (ngModelChange)="postQuotationDatas($event,products,'longueur')" type="number">
    </a>
    <input class="mb-1 flex1 checkbox" ngModel="{{products.hasValve}}"  (ngModelChange)="postQuotationDatas($event,products,'hasValve')" type="checkbox">
    <a class="flex1 mb-1">
      <input class="number" ngModel="{{products.quantity}}"  (ngModelChange)="postQuotationDatas($event,products,'quantity')" type="number">
    </a>
    <a class="flex1">
      {{(products.total_fourniture)}}
    </a>
  </div>
</div>

【问题讨论】:

  • 你能提供一个带有预期输出对象的虚拟输入对象吗好像你需要为此编写一个自定义函数

标签: arrays angular typescript


【解决方案1】:

考虑以下 sn-p:

// assume arr refers to your array of data
const groups = {}; // for storing groups while processing
arr.forEach(v => {
    if(groups[v.part_image]) 
        groups [v.part_image].push(v.image); // the actual image values you want to group
    else groups[v.part_image] = [ v.image ];
});
// Now you can process each image and all its parts

您可以遍历对象中的所有键。 Object.keys(groups)

【讨论】:

  • 你错过了 if 块的右括号
  • 非常感谢!这是一个非常好的输入,所以为了在前面只渲染一次图像,我在之后使用Object.keys(groups),对吧?
  • @Zephyr 是的。一旦您调用Object.keys(groups),它将返回组对象的所有键。密钥按“随机”顺序排列。如果您需要以任何方式对其进行排序,您可以尝试在获取密钥后链接sort()。您可以将每个对象读取为Object.keys(groups).forEach(k =&gt; grouos[k]);。希望能解释。如果您需要更多帮助,请发表评论。如果 sn-p 解决了您的问题,则标记为已接受。谢谢
猜你喜欢
  • 2017-06-15
  • 2014-09-16
  • 1970-01-01
  • 1970-01-01
  • 2018-03-12
  • 2013-10-22
  • 1970-01-01
  • 2020-08-09
  • 2017-12-13
相关资源
最近更新 更多