オブジェクトの配列から始めて、すべてのキーのリストとそれぞれのすべての固有の値を取得する必要があります。問題は私が事前にキーを知らないことです。キーを知っていれば、たくさんの解決法がありますが、この場合、各オブジェクトは任意の数のキーを持ち、各キーは値の配列を持ちます。以下のコードは動作しますが、非常に複雑で簡単な解決策が必要です。アンダースコアを使用してそれぞれの固有の値とキーを取得する
入力:
[
{
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();
完璧!それはまさに私が探していたものです。ありがとう! –
あなたは大歓迎です:) –