gpt4 book ai didi

javascript - 将复杂对象转换为表格格式(平面)

转载 作者:行者123 更新时间:2023-12-02 23:03:31 29 4
gpt4 key购买 nike

我有一个对象:

[
{
TEAMGROUP: "AB",
TEAMNAME: "TEAM1",
SPRINTS: [
{
ID: 1,
NAME: "Name",
STATE: "Open",
GOAL: "Goal goes here",
ESTIMATED: 5,
COMPLETED: 3
},
{
ID: 2,
NAME: "Name",
STATE: "In Progress",
GOAL: "Goal goes here",
ESTIMATED: 8,
COMPLETED: 12
}
]
},
{
TEAMGROUP: "AB",
TEAMNAME: "TEAM2",
SPRINTS: [
{
ID: 4,
NAME: "Name",
STATE: "Closed",
GOAL: "Goal goes here",
ESTIMATED: 4,
COMPLETED: 1
},
//...
]
},
//...
]

我希望它变成

[
{
TEAMGROUP: "AB",
TEAMNAME: "TEAM1",
ID: 1,
NAME: "Name",
STATE: "Open",
GOAL: "Goal goes here",
ESTIMATED: 5,
COMPLETED: 3
},
{
TEAMGROUP: "AB",
TEAMNAME: "TEAM1",
ID: 2,
NAME: "Name",
STATE: "In Progress",
GOAL: "Goal goes here",
ESTIMATED: 8,
COMPLETED: 12
},
{
TEAMGROUP: "AB",
TEAMNAME: "TEAM2",
ID: 4,
NAME: "Name",
STATE: "Closed",
GOAL: "Goal goes here",
ESTIMATED: 4,
COMPLETED: 1
},
//...
]

我尝试了.map和.flatMap的各种配置。但我无法得到我需要的确切结果。

我已经尝试过:

    let teamData = this.filteredData.map( team =>
team.sprints.map( sprint => sprint ) ).flat();

以及其他此类变体。此示例正确返回展平数组,但未返回 teamGroup 或 teamName。

我也尝试过类似的方法:

    const teamData = this.filteredData.map( ( { teamName, teamGroup, months }, i ) => ( {
teamName, teamGroup, months: months.flat()
} ) );

但这不会使月份变平并返回所有内容。

最佳答案

首先为您的 JSON 对象创建一个模型:

class MyModel {
TEAMGROUP: string;
TEAMNAME: string;
ID: number;
NAME: string;
STATE: string;
GOAL: string;
ESTIMATED: number;
COMPLETED: number;
}

然后循环遍历第一级和第二级数组。在每个循环中创建一个对象并将其推送到新数组:

const array = [{
TEAMGROUP: 'AB',
TEAMNAME: 'TEAM1',
SPRINTS: [{
ID: 1,
NAME: 'Name',
STATE: 'Open',
GOAL: 'Goal goes here',
ESTIMATED: 5,
COMPLETED: 3
},
{
ID: 2,
NAME: 'Name',
STATE: 'In Progress',
GOAL: 'Goal goes here',
ESTIMATED: 8,
COMPLETED: 12
}
]
}];

const newArray = [];
for (const item of array) {
const newItem = new MyModel();
newItem.TEAMNAME = item.TEAMNAME;
newItem.TEAMGROUP = item.TEAMGROUP;

for (const sprint of item.SPRINTS) {
newItem.ID = sprint.ID,
newItem.NAME = sprint.NAME,
newItem.STATE = sprint.STATE,
newItem.GOAL = sprint.GOAL,
newItem.ESTIMATED = sprint.ESTIMATED,
newItem.COMPLETED = sprint.COMPLETED;

newArray.push(newItem);
}
}

关于javascript - 将复杂对象转换为表格格式(平面),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57697891/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com