我有array
个像这样的对象:
[
{"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中提取公共值并创建如下所示的多维数组的最简单方法是什么?
[
["v1", [27172, 15177, 19411]],
["v2", [30163, 23949, 23829, 27821]]
];
答案 0 :(得分:3)
这是一个带有一些循环的解决方案。
我在这里创建了一个jsbin:http://jsbin.com/cucixi/edit?html,js,console
var list = [
{"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 data = {};
list.forEach(function(item){
if (item.k1 in data){
data[item.k1].push(item.k2);
} else {
data[item.k1] = [item.k2];
}
});
var output = [];
for (var key in data){
output.push([key, data[key]]);
}
console.log(output);
输出:
[
["v1", [27172, 27172, 15177, 15177, 19411, 19411]],
["v2", [30163, 30163, 23949, 23949, 23829, 23829, 27821, 27821]]
]
答案 1 :(得分:3)
使用数组的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]]
];
答案 2 :(得分:2)
jsfiddle:https://jsfiddle.net/aLnc9oh1/
解决方案:
function solution(A)
{
// make an object with an array of values
var temp = {};
for (var i=0, ii=A.length; i<ii; i++)
{
var prop = A[i]['k1'];
if (temp[prop])
temp[prop].push(A[i]['k2']);
else
temp[prop] = [A[i]['k2']];
}
// reformat that into the 2D array like desired
var retArr = [];
for (var key in temp)
retArr.push([key, temp[key]]);
// return it!
return retArr;
}
对于给定的数据返回:
[
["v1", [27172, 15177, 19411]],
["v2", [30163, 23949, 23829, 27821]]
]
答案 3 :(得分:0)
您可能希望使用Array.prototype.map()
和Object.keys()
var obj = data.reduce((acc, x) => {
acc[x.k1] = (acc[x.k1] || []).concat(x.k2));
return acc;
}, {});
var res = Object.keys(obj).map(x => [x, obj[x]]);