gpt4 book ai didi

javascript - 如何停止为值复制键

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

我有一个序列号数组。它可以看起来像这样。

lot: 1  Serial: 2
lot: 1 Serial: 3
lot: 1 Serial: 4

...等等。或者看起来像

lot: 1  Serial: 5
lot: 1 Serial: 9
lot: 8 Serial: 2
lot: 8 Serial: 4

var dictSerials = []
if (serialNumbers.length > 0)
for (var i of serialNumbers) {
dictSerials.push({
key: i.value.lot,
value: i.value.serial
})
}

这是我试图用来使事情正常运行的方法,但这会为列出的每个创建一个键和值。我希望我的结果是这样的对象:

Key: 1  Value: 2, 3, 4, 5, 9
Key: 8 Value: 2, 4

谁能帮我解决这个问题?谢谢!

最佳答案

满足您要求的另一种方法是使用函数 reduce 对键和值进行分组。

let array = [{lot: 1, Serial: 2},{lot: 1, Serial: 3},{lot: 1, Serial: 4},{lot: 1, Serial: 5},{lot: 1,Serial: 9},{lot: 8,Serial: 2},{lot: 8,Serial: 4}],
result = Object.values(array.reduce((a, c) => {
(a[c.lot] || (a[c.lot] = {Key: c.lot, Value: []})).Value.push(c.Serial);
return a;
}, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何停止为值复制键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50239502/

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