gpt4 book ai didi

javascript - 替换对象数组

转载 作者:行者123 更新时间:2023-11-28 14:25:57 25 4
gpt4 key购买 nike

我有以下对象数组

const array = [
{ home1: "05:45", dayOfWeek: 1, away: "09:30"},
{ home1: "05:15", dayOfWeek: 2, away: "09:30"},
{ home1: "17:30", dayOfWeek: 5, away: "09:30"},
{ home1: "16:30", dayOfWeek: 7, away: "09:30"}
]

我有四个 dayOfWeek (1,2,5,7)。现在我需要使用虚拟对象推送剩余的三个(3,4,6) ({ home1: "05:30", dayOfWeek: 7,away: "09:30"})

现在逻辑部分是我不知道数组中存在哪个dayOfWeek。可能只有一个、两个、三个或空白。我每次都需要在该数组中推送 7 天。

如何做到这一点?请建议我最好的方法

谢谢!!!

最佳答案

一种选择是对数组中迄今为止包含的日期进行Set,然后从 1 迭代到 7,push 将新对象推送到数组中如果该天不包含在集合中:

const array = [
{ home1: "05:45", dayOfWeek: 1, away: "09:30"},
{ home1: "05:15", dayOfWeek: 2, away: "09:30"},
{ home1: "17:30", dayOfWeek: 5, away: "09:30"},
{ home1: "16:30", dayOfWeek: 7, away: "09:30"}
];
const dummy = { home1: "05:30", away: "09:30" };
const days = new Set(array.map(({ dayOfWeek }) => dayOfWeek));
for (let i = 1; i <= 7; i++) {
if (!days.has(i)) array.push({ ...dummy, dayOfWeek: i });
}
console.log(array);

我使用了 Set 来降低复杂性,但我想如果您只需要 7 个对象,那并不重要,您可以使用 find 而无需创建预先收集

const array = [
{ home1: "05:45", dayOfWeek: 1, away: "09:30"},
{ home1: "05:15", dayOfWeek: 2, away: "09:30"},
{ home1: "17:30", dayOfWeek: 5, away: "09:30"},
{ home1: "16:30", dayOfWeek: 7, away: "09:30"}
];
const dummy = { home1: "05:30", away: "09:30" };
for (let i = 1; i <= 7; i++) {
if (!array.find(({ dayOfWeek }) => dayOfWeek === i)) {
array.push({ ...dummy, dayOfWeek: i });
}
}
console.log(array);

关于javascript - 替换对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53257768/

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