从一组对象开始,我需要获取所有键的列表以及每个键的所有唯一值。问题是我事先不知道密钥。如果您知道密钥,有很多解决方案,但在这种情况下,每个对象可以有任意数量的密钥,每个密钥都有一组值。下面的代码工作,但它很复杂,必须有一个更简单的解决方案。使用下划线获取所有键和每个键的唯一值列表
输入:
[
{
key_1: [ attribute_value_1, attribute_value_2, ... ],
key_2: [ attribute_value_3, attribute_value_4, ... ],
},
...
]
输出:
[
{
label: key_1,
options: [ attribute_value_1, attribute_value_2, ... ]
},
{
label: key_2,
options: [ attribute_value_3, attribute_value_4, ... ]
},
...
]
建议的解决方案:
_.chain(input)
.map(function (attr) {
return _.keys(attr).map(function (key) {
return {
key: key,
value: attr[key]
};
});
})
.flatten()
.groupBy('key')
.map(function (grouped_values, key) {
// value = array of { key, value }
return {
label: key,
options: _.chain(grouped_values)
.pluck('value')
.flatten()
.uniq()
.value()
};
})
.value();
完美!这正是我所期待的。谢谢! –
不客气:) –