Javascript:如何使用已排序的唯一数组将对象数组转换为对象? [英] Javascript: How convert array of objects to object with sorted unique arrays?
问题描述
拥有具有此类结构的数据:
Have data that has this kind of structure:
$input = [ { animal: 'cat', name: 'Rocky', value: 1 },
{ animal: 'cat', name: 'Spot', value: 2 },
{ animal: 'dog', name: 'Spot', value: 3 } ];
需要尽可能快的方法转换为此格式:
Need fastest possible method for converting to this format:
$output = { animal: [ 'cat', 'dog' ],
name: [ 'Rocky', 'Spot' ],
value: [ 1, 2, 3 ] };
输出的键应等于输入中每个对象中的每个键。并且输出值应该是具有已排序的唯一值的数组。我发现了一些使用嵌套循环的方法,但比我想要的慢。输入数组有30,000个元素,每个对象有8个键,我能做的最好的是Chrome中的300ms。想要降到100毫秒。有没有更快的方法使用map或reduce?
The output should have keys equal to each of the keys in each object from the input. And the output values should be arrays with the sorted unique values. I found a few ways to do it using nested loops, but slower than I would like. With 30,000 elements to the input array with 8 keys for each of the objects, the best I have been able to do is 300ms in Chrome. Would like to get down to 100ms. Is there any faster method using a map or reduce?
推荐答案
这是单向的。
$input = [ { animal: 'cat', name: 'Rocky', value: 1 },
{ animal: 'cat', name: 'Spot', value: 2 },
{ animal: 'dog', name: 'Spot', value: 3 } ];
$output = {animal:{},name:{},value:{}};
$input.forEach(function(v,i) {
$output.animal[v.animal] = 1;
$output.name[v.name] = 1;
$output.value[v.value] = 1;
});
$output.animal = Object.keys($output.animal);
$output.name = Object.keys($output.name);
$output.value = Object.keys($output.value);
它可以防止每次都要测试每个数组。您可以进行性能比较,看看是否有帮助。
It prevents having to test each Array every time. You can performance compare to see if it helps.
实例 http://jsfiddle.net/TJVtj/1/
如果您不想对密钥进行硬编码,可以使解决方案通用。
If you don't want to hardcode the keys, you can make the solution generic.
var keys = Object.keys($input[0]),
$output = {};
keys.forEach(function(v) {
$output[v] = {};
});
$input.forEach(function(v) {
keys.forEach(function(vv) {
$output[vv][v[vv]] = 1;
});
});
keys.forEach(function(v) {
$output[v] = Object.keys($output[v]);
});
实例 http://jsfiddle.net/TJVtj/2/
警告。所有值都是字符串,因为它们被提取为对象键。
这篇关于Javascript:如何使用已排序的唯一数组将对象数组转换为对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!