gpt4 book ai didi

javascript - 如何组合具有相同键的对象而不覆盖值?

转载 作者:行者123 更新时间:2023-12-02 22:09:45 24 4
gpt4 key购买 nike

我试图通过相同的键组合对象数组,而不是覆盖这些值。是否可以将这些值组合到一个数组中以引用相同的键引用。

考虑这个日历对象:

const calendar = [
{date: "1999", month: "03"},
{date: "1999", month: "01"},
{date: "1998", month: "04"}
]

// My attempted with lodash:
let results = _(calendar )
.groupBy('date')
.value()

// my output (also returns an object)
results = {
1998: {date: "1998", month: "04"}
1999: {date: "1999", month: "03"}, {date: "1999", month: "01"}
}

// Acceptable Output #1:
results = [
{date: "1999", month: ["03", "01"]},
{date: "1998", month: ["04"]}
]

// Acceptable Output #2:
results = {
1998: [{month: "04"}]
1999: [{month: "03"}, {month: "01"}]
}

// Acceptable Output #3:
results = [
{"1999": ["03", "01"]},
{"1998": ["04"]}
]


或者如果有其他可行的替代方案。最终目标是不覆盖我在 stackoverflow 上看到的所有值......

最佳答案

您可以使用 reduce 而不是使用 lodash 库。

输出 3

const calendar = [
{date: "1999", month: "03"},
{date: "1999", month: "01"},
{date: "1998", month: "04"}
];

const output = calendar
.reduce((a, {date, month}) => {
if(!a[date]) {
a[date] = [];
}

a[date].push(month);
return a;
}, {});

console.log(output);

输出 2

const calendar = [
{date: "1999", month: "03"},
{date: "1999", month: "01"},
{date: "1998", month: "04"}
];

const output = calendar
.reduce((a, {date, month}) => {
if(!a[date]) {
a[date] = [];
}

a[date].push({month});
return a;
}, {});

console.log(output);

输出 1

const calendar = [
{date: "1999", month: "03"},
{date: "1999", month: "01"},
{date: "1998", month: "04"}
];

const output = calendar
.reduce((a, {date, month}) => {
if(!a[date]) {
a[date] = {date, month: []};
}

a[date].month.push(month);
return a;
}, {});

console.log(Object.values(output));

关于javascript - 如何组合具有相同键的对象而不覆盖值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59596829/

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