2次元配列にしてからflattenで1次元配列に叩き落とすか、
reduceで2次元配列→1次元配列に戻しながら格納するかの二択ですね。
こんな感じでいかが?
JavaScript
1const make = (tmpList, groups) =>
2 _(tmpList)
3 .map(tmp =>
4 _.map(groups, group => ({...tmp, id: group.id}))
5 )
6 .flatten()
7 .values()
8
9const users = [
10 { user: 'barney', age: 36, active: true },
11 { user: 'fred', age: 40, active: false },
12 { user: 'travis', age: 37, active: true}
13];
14const ids = [
15 { id: 123 },
16 { id: 234 }
17];
18console.log(make(users, ids));
19// いい感じにでました
【おまけ】
reduce使うルートならネイティブJSでも出来そうなのでやりました。
JavaScript
1const make = (tmpList, groups) =>
2 tmpList
3 .map(tmp => groups.map(group => ({...tmp, id: group.id})))
4 .reduce((arr, items) => {
5 items.forEach(it => { arr.push(it) });
6 return arr;
7 }, [])
8
9const users = [
10 { user: 'barney', age: 36, active: true },
11 { user: 'fred', age: 40, active: false },
12 { user: 'travis', age: 37, active: true}
13];
14const ids = [
15 { id: 123 },
16 { id: 234 }
17];
18console.log(make(users, ids));
19// こちらもいい感じの結果に
【追記】 グループ分けしたオブジェクトへの対応版
条件変わってますので再度考え直してみます。
まぁ、オブジェクトはtoPairsを使って配列にしてしまえば消化試合です。
キーに引っかかるグループが存在しなかった場合を考慮して、
存在しないグループは一度filterで消し飛ばすというガードも組み込みました。
JavaScript
1const list = {
2 'sports': [
3 {identify: 'soccer', name: 'サッカー'},
4 {identify: 'baseball', name: '野球'}
5 ],
6 'nature': [
7 {identify: 'animal', name: '動物'},
8 {identify: 'flower', name: '花'}
9 ]
10};
11const groups = [
12 {identify:'sports', id: 1},
13 {identify:'nature', id: 2},
14];
15
16const make = (tmpList, groups) =>
17 _(tmpList)
18 .toPairs()
19 .filter(([gname]) => _.find(groups, group => group.identify === gname))
20 .map(([gname, items]) => {
21 const group = _.find(groups, group => group.identify === gname);
22 return _.map(items, it => ({...it, group_id: group.id}));
23 })
24 .flatten()
25 .value()
26
27result = make(list, groups)
https://codepen.io/travist/full/jrBjBz/にコピペすればちゃんと表示されることがわかります。
結果:
JSON
1[
2 {
3 "identify": "soccer",
4 "name": "サッカー",
5 "group_id": 1
6 },
7 {
8 "identify": "baseball",
9 "name": "野球",
10 "group_id": 1
11 },
12 {
13 "identify": "animal",
14 "name": "動物",
15 "group_id": 2
16 },
17 {
18 "identify": "flower",
19 "name": "花",
20 "group_id": 2
21 }
22]