簡體   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