javascript - 如何在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;
});
}),
);
解决方案
- 使用两个级别的 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);
- 或者在 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);
推荐阅读
- c# - 新来的,需要帮助才能“行动”一次
- spring - spring security 如何支持多种授权方式
- linq - C# LINQ Any() 比较两个列表
- php - Yii2,从两个连接表中选择作为 ActiveRecord
- javascript - Web-Bluetooth API,不能更新特性。时间相关的更新可能吗?
- php - Laravel 未在共享服务器上显示图像形式的存储
- javascript - JavaScript获取位于不同文件夹中的不带扩展名的文件名
- amazon-web-services - 我们可以在 eks 上创建两个控制器吗?一个是 nginx 入口控制器和 alb 入口控制器
- dataset - 人体姿势数据集 pcd 文件
- c# - 无法调用方法 endgame()