gpt4 book ai didi

javascript数组转换为特定格式

转载 作者:行者123 更新时间:2023-11-30 14:24:37 26 4
gpt4 key购买 nike

对象数组是动态的

Activity可以分为四种(Idle, Down, Up, Waiting)

如果事件状态为打开,下一个事件状态为关闭,但事件相同。

如何转换成我期望的输出?

var arr = [
{ Activity: 'Idle', Activity_Status: 'Open', Activity_Date: "2018-09-02T12:30:00.000Z" },
{ Activity: 'Idle', Activity_Status: 'Close', Activity_Date: "2018-09-02T14:00:00.000Z"},
{ Activity: 'Down', Activity_Status: 'Open', Activity_Date: "2018-09-02T17:30:00.000Z" },
{ Activity: 'Down', Activity_Status: 'Close', Activity_Date: "2018-09-02T19:00:00.000Z"}
]

预期输出是:

[
{ Activity: 'Idle', From: "2018-09-02T12:30:00.000Z", To: "2018-09-02T14:30:00.000Z" },
{ Activity: 'Down', From: "2018-09-02T17:30:00.000Z", To: "2018-09-02T19:00:00.000Z" }
]

最佳答案

由于 open 状态紧跟其相应的 close 状态,使用一个简单的 for 循环,通过执行 i += 2 并且每次迭代合并当前对象和下一个对象,如下所示:

var result = [];
for(var i = 0; i < arr.length; i += 2) {
result.push(
{ Activity: arr[i].Activity, From: arr[i].Activity_Date, To: arr[i + 1].Activity_Date }
);
}

示例:

var arr = [ { Activity: 'Idle', Activity_Status: 'Open', Activity_Date: "2018-09-02T12:30:00.000Z" }, { Activity: 'Idle', Activity_Status: 'Close', Activity_Date: "2018-09-02T14:00:00.000Z"}, { Activity: 'Down', Activity_Status: 'Open',  Activity_Date: "2018-09-02T17:30:00.000Z" }, { Activity: 'Down', Activity_Status: 'Close', Activity_Date: "2018-09-02T19:00:00.000Z"} ];

var result = [];
for(var i = 0; i < arr.length; i += 2) {
result.push(
{ Activity: arr[i].Activity, From: arr[i].Activity_Date, To: arr[i + 1].Activity_Date }
);
}

console.log(result);

如果你想要一个功能性的方式来做到这一点,那么:

let result = Array.from({length: arr.length / 2}).map((_, i) =>
({ Activity: arr[i].Activity, From: arr[i].Activity_Date, To: arr[i + 1].Activity_Date })
);

示例:

var arr = [ { Activity: 'Idle', Activity_Status: 'Open', Activity_Date: "2018-09-02T12:30:00.000Z" }, { Activity: 'Idle', Activity_Status: 'Close', Activity_Date: "2018-09-02T14:00:00.000Z"}, { Activity: 'Down', Activity_Status: 'Open',  Activity_Date: "2018-09-02T17:30:00.000Z" }, { Activity: 'Down', Activity_Status: 'Close', Activity_Date: "2018-09-02T19:00:00.000Z"} ];

let result = Array.from({length: arr.length / 2}).map((_, i) =>
({ Activity: arr[i].Activity, From: arr[i].Activity_Date, To: arr[i + 1].Activity_Date })
);

console.log(result);

关于javascript数组转换为特定格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52139663/

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