gpt4 book ai didi

javascript - 从键中提取公共(public)值并制作多维数组

转载 作者:行者123 更新时间:2023-11-30 07:21:57 24 4
gpt4 key购买 nike

我有一个像这样的对象的数组:

[
{"k1":"v1","k2":27172},
{"k1":"v1","k2":15177},
{"k1":"v1","k2":19411},
{"k1":"v2","k2":30163},
{"k1":"v2","k2":23949},
{"k1":"v2","k2":23829},
{"k1":"v2","k2":27821}
]

从 k1 中提取公共(public)值并创建如下所示的多维数组的最简单方法是什么?

[
["v1", [27172, 15177, 19411]],
["v2", [30163, 23949, 23829, 27821]]
];

最佳答案

使用数组的reduce函数

var test = [
{ "k1": "v1", "k2": 27172 },
{ "k1": "v1", "k2": 15177 },
{ "k1": "v1", "k2": 19411 },
{ "k1": "v2", "k2": 30163 },
{ "k1": "v2", "k2": 23949 },
{ "k1": "v2", "k2": 23829 },
{ "k1": "v2", "k2": 27821 }
]

var out = test.reduce(function(res, obj) {
res[obj.k1] = res[obj.k1] || [];
res[obj.k1].push(obj.k2)
return res;
}, {});

var result = [];
for (var key in out) {
result.push([key, out[key]])
};

console.log(JSON.stringify(result, null, 2))

会给予

[
["v1", [27172, 15177, 19411]],
["v2", [30163, 23949, 23829, 27821]]
];

关于javascript - 从键中提取公共(public)值并制作多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37122817/

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