繁体   English   中英

如何遍历 Typescript 中具有数组和对象的大型数组列表

[英]How to traverse large array list having array and Objects in Typescript

我有一个数组。 每个索引都有 Object 数组,它至少有 10 个属性,我想通过所有对象 map 并以相同的顺序仅存储这些对象的 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;
        });
    }),
  );
  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);

试试这个,

 let companyUserIds = []; organisationCompanyTalents.map(orgCmpTalent => { for (let i=0; i<orgCmpTalent.length; i++){ companyUserIds.push(orgCmpTalent[i].id) } });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM