gpt4 book ai didi

javascript - 按 Javascript 对象键 + 数组分组

转载 作者:行者123 更新时间:2023-11-30 11:44:12 28 4
gpt4 key购买 nike

我正在尝试使用下划线将我的对象数组分组到一个较小的列表中:

    var list = [
{ Region: 'A', Vals: [ 7, 'H' ] },
{ Region: 'B', Vals: [ 40, 'H' ] },
{ Region: 'B', Vals: [ 24, 'VH' ] },
{ Region: 'C', Vals: [ 4, 'VH' ] },
{ Region: 'A',Vals: [ 40, 'VH' ] }
];


var groups = _.groupBy(list, function(value){
return value.Region;
});

var grouped = _.map(groups, function(group){
return {
Region: group[0].Region,
Vals: group[0].Vals
}
});

它会变得有些接近,但它缺少一些 Vals。我想要基于键连接的“vals”数组。

   var list = [
{ Region: 'A', Vals: [ 7, 'H', 40, 'VH' ] },
{ Region: 'B', Vals: [ 40, 'H', 24, 'VH' ] },
{ Region: 'B', Vals: [ 24, 'VH' ] },
{ Region: 'C', Vals: [ 4, 'VH' ] }
];

http://jsfiddle.net/77gL11c9/1/

最佳答案

list.reduce(function (memo, v) {
if (memo[v.Region]) {
memo[v.Region] = memo[v.Region].concat(v.Vals)
} else {
memo[v.Region] = v.Vals.slice()
}
return memo
}, {})

输出将如下所示:

{
A: [ 7, "H", 40, "VH" ],
B: [40, "H", 24, "VH" ],
C: [ 4, "VH" ]
}

关于javascript - 按 Javascript 对象键 + 数组分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41554523/

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