首页 > 解决方案 > 如何在Typescript中遍历具有数组和对象的大型数组列表

问题描述

我有一个数组。每个索引都有至少有 10 个属性的对象数组,我想映射所有对象并以相同的顺序仅存储这些对象的 id。我为此编写了这段代码。

这是我的数据结构

organisationCompanyTalents = [
    [
      {
        id: '',
        fname: '',
        lname: '',
        other1: '',
      },
      {
        id: '',
        fname: '',
        lname: '',
        other1: '',
      },
    ],
    [
      {
        id: '',
        fname: '',
        lname: '',
        other1: '',
      },
    ],
  ];

let companyUserIds = Array();

  organisationCompanyTalents.map(orgCmpTalent => {
    let list = Array();
    orgCmpTalent.map(companyTalent => {
      list.push(companyTalent.company_user_id);
    }),
      companyUserIds.push(list);
  });

现在这个代码的问题是它不是总是以相同的顺序存储 id,有时较大的数组被遍历并首先存储,有时是较小的数组。我怎样才能使它高效,以便它以相同的顺序返回。

数据获取部分:

let organisationCompanyTalents = Array();
var orgTalentReview = Array();

if (companyOrganisations.length > 0) {
  await Promise.all(
    companyOrganisations.map(async org => {
      await this.ComapanyTalentService.getCompanyTalentByOrganisationId(
        org._id,
        companyUser.Company_Id,
      )
        .then(companyTalent => {
          if (companyTalent) {
            organisationCompanyTalents.push(Object.values(companyTalent));
          }
        })
        .catch(error => {
          throw error;
        });
    }),
  );

标签: javascriptnode.jstypescript

解决方案


  1. 使用两个级别的 forEach 循环,如下所示:

const organisationCompanyTalents = [
    [
      {
        id: 6,
        fname: 'fname6',
        lname: 'lname6',
        other1: 'other16',
      },
      {
        id: 4,
        fname: 'fname4',
        lname: 'lname4',
        other1: 'other14',
      },
    ],
    [
      {
        id: 9,
        fname: 'fname9',
        lname: 'lname9',
        other1: 'other19',
      },
    ],
  ];

let companyUserIds: any[] = [];

  organisationCompanyTalents.forEach(talents => {
      let ids: any[] = [];
      talents.forEach(talent => {
          ids.push(talent.id);
      });

      companyUserIds.push(ids);
  });

  console.clear();
  console.log(companyUserIds);

  1. 或者在 forEach 循环中使用 map:

const organisationCompanyTalents = [
    [
        {
            id: 6,
            fname: 'fname6',
            lname: 'lname6',
            other1: 'other16',
        },
        {
            id: 4,
            fname: 'fname4',
            lname: 'lname4',
            other1: 'other14',
        },
    ],
    [
        {
            id: 9,
            fname: 'fname9',
            lname: 'lname9',
            other1: 'other19',
        },
    ],
];

let companyUserIds: any[] = [];

organisationCompanyTalents.forEach(talents => {
    let ids = [];
    ids.push(...talents.map(talent => talent.id));
    companyUserIds.push(ids);
});

console.clear();
console.log(companyUserIds);


推荐阅读