Javascript 如何组合具有相同键的对象而不重写值?
我试图通过同一个键组合一个对象数组,而不是覆盖这些值。是否可以将这些值组合到同一个键引用的数组中 考虑以下日历对象:Javascript 如何组合具有相同键的对象而不重写值?,javascript,arrays,object,key-value,Javascript,Arrays,Object,Key Value,我试图通过同一个键组合一个对象数组,而不是覆盖这些值。是否可以将这些值组合到同一个键引用的数组中 考虑以下日历对象: const calendar = [ {date: "1999", month: "03"}, {date: "1999", month: "01"}, {date: "1998", month: "04"} ] // My attempted with lodash: let results = _(calendar ) .groupBy('date
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
常量日历=[
{日期:1999年,月份:03},
{日期:1999年,月份:01},
{日期:1998年,月份:04}
];
常量输出=日历
.reducea,{date,month}=>{
如果!a[日期]{
a[日期]=[];
}
a[日期].月份;
返回a;
}, {};
console.logoutput@隐形编码器-欢迎。如果要使用lodash,请使用_values-,这与您得到的结果中的Object.values类似。