gpt4 book ai didi

javascript - 动态重组对象数组,每个对象包含两个属性值对

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

我正在从数据库中提取数据,最终得到一个对象数组,每个对象都包含服务员姓名和他们工作的天数。我想通过将数组压缩为每个服务员具有两个属性值对的单个对象来动态重组数组。一个属性用于名称,另一个属性用于工作日期。

我真的很想看到您的反馈。我首先提取名称并删除重复项。给我留下一个像这样的数组:let waiterNames = ['John','Mark','Jess'].

然后我尝试使用双 for of 循环并以某种方式创建一个新的对象数组,但我陷入困境。

for (entry in waiterInfo) {
for (waiter in waiterNames) {
if (entry.waiters == waiter) {
???
}
}
}

waiterInfo 是我开始的内容,newInfo 是我想要实现的目标。我需要动态发生这种情况,因为从数据库中提取的数据是不可预测的。

let waiterInfo = [{ waiters: 'John', weekdays: 'Monday' },
{ waiters: 'John', weekdays: 'Tuesday' },
{ waiters: 'John', weekdays: 'Wednesday' },
{ waiters: 'Mark', weekdays: 'Monday' },
{ waiters: 'Mark', weekdays: 'Tuesday' },
{ waiters: 'Jess', weekdays: 'Monday' },
{ waiters: 'Jess', weekdays: 'Tuesday' },
{ waiters: 'Jess', weekdays: 'Wednesday' },
{ waiters: 'Jess', weekdays: 'Thursday' }]
let newInfo = [{ waiters: 'John', weekdays: 'Monday, Tuesday, Wednesday'},
{ waiters: 'Mark', weekdays: 'Monday, Tuesday' },
{ waiters: 'Jess', weekdays: 'Monday, Tuesday, Wednesday, Thursday' }]

最佳答案

您可以将 map 与reduce一起使用:

let waiterInfo = [{ waiters: 'John', weekdays: 'Monday' },
{ waiters: 'John', weekdays: 'Tuesday' },
{ waiters: 'John', weekdays: 'Wednesday' },
{ waiters: 'Mark', weekdays: 'Monday' },
{ waiters: 'Mark', weekdays: 'Tuesday' },
{ waiters: 'Jess', weekdays: 'Monday' },
{ waiters: 'Jess', weekdays: 'Tuesday' },
{ waiters: 'Jess', weekdays: 'Wednesday' },
{ waiters: 'Jess', weekdays: 'Thursday' }
]


const map = new Map()

const newInfo = waiterInfo.reduce((a, o) => {
const i = map.get(o.waiters)
if(i !== undefined) {
a[i].weekdays = [a[i].weekdays, o.weekdays].join(', ')
} else {
map.set(o.waiters, a.push(o) - 1)
}
return a
}, [])

console.log(newInfo)

这段代码的时间复杂度是 O(n),因为我们使用的是 map 。

(此外,这是我见过 push 的返回值有用的唯一一次 😜)

关于javascript - 动态重组对象数组,每个对象包含两个属性值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58589610/

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