從一組對象開始,我需要獲取所有鍵的列表以及每個鍵的所有唯一值。問題是我事先不知道密鑰。如果您知道密鑰,有很多解決方案,但在這種情況下,每個對象可以有任意數量的密鑰,每個密鑰都有一組值。下面的代碼工作,但它很複雜,必須有一個更簡單的解決方案。使用下劃線獲取所有鍵和每個鍵的唯一值列表
輸入:
[
{
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();
完美!這正是我所期待的。謝謝! –
不客氣:) –