gpt4 book ai didi

javascript - 如何使用 switch case 将包含字符串的值放入数组中的正确对象中?

转载 作者:行者123 更新时间:2023-11-30 23:59:50 26 4
gpt4 key购买 nike

我有一个 data 数组,如下所示:

{
"data": [
{
"season": "autumn",
"firstContactPersonName": "John",
"firstContactPersonPhone": "46442644",
"secondContactPersonName": "Jhonny",
"secondContactPersonPhone": "46442644"
},
{
"season": "christmas",
"firstContactPersonName": "Tommy",
"firstContactPersonPhone": "46442644",
"secondContactPersonPhone": "Thomas"
},
{
"season": "winter",
"firstContactPersonPhone": "46442644",
"firstContactPersonName": "Peter",
"secondContactPersonName": "Tom",
"secondContactPersonPhone": "44664455"
}
]
}

但有时可能会有:

{
"data": [
{
"season": "christmas",
"firstContactPersonName": "Tommy",
"firstContactPersonPhone": "46442644",
"secondContactPersonPhone": "Thomas"
},
{
"season": "autumn",
"firstContactPersonName": "John",
"firstContactPersonPhone": "46442644",
"secondContactPersonName": "Jhonny",
"secondContactPersonPhone": "46442644"
}
]
}

data 数组可以更改。

我有另一个包含一些日期的数组。它们在数组中具有以下日期:

const dateArray = ["christmas=2020-12-28", "autumn=2020-08-28", "winter=2020-02-28"]

有时可以有 const dateArray = ["christmas=2020-12-28", "autumn=2020-08-28"]

如何将 data 数组中的这些日期插入到正确的对象中,而不实际告诉对象位于哪个位置?我如何找到秋季、圣诞节或冬季的位置,然后将正确的日期放入正确的对象中?如果我向 data 数组添加新对象会怎样?换句话说,我需要一些动态方法来为我处理它。所以我可以在 = 之前添加新键到日期并插入到 data 数组中的正确对象。

最佳答案

let data = [
{
"season": "autumn",
"firstContactPersonName": "John",
"firstContactPersonPhone": "46442644",
"secondContactPersonName": "Jhonny",
"secondContactPersonPhone": "46442644"
},
{
"season": "christmas",
"firstContactPersonName": "Tommy",
"firstContactPersonPhone": "46442644",
"secondContactPersonPhone": "Thomas"
},
{
"season": "winter",
"firstContactPersonPhone": "46442644",
"firstContactPersonName": "Peter",
"secondContactPersonName": "Tom",
"secondContactPersonPhone": "44664455"
}
]

const dateArray = ["christmas=2020-12-28", "autumn=2020-08-28", "winter=2020-02-28"]
let updatedData = data.map((x)=> {
let season = x.season;
x.date = dateArray.find(e=> e.indexOf(season) > -1).split("=")[1];
return x;
})


console.log(updatedData)

关于javascript - 如何使用 switch case 将包含字符串的值放入数组中的正确对象中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60804038/

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