2017-08-03 54 views
0

我使用一些複雜的數據對象,並且需要動態地將一些數據從子節點映射到父節點,遞歸地直到頂層。拋開細節,我在下面的操作堆棧。最低級的孩子和他們的父母立即,然後將這個遞歸地應用於父母之間: 用lodash對子值進行遞歸分組

[ 
    [ 
    ['key 1', 1], 
    ['key 2', null], 
    ['key 3', 42] 
    ], 
    [ 
    ['key 1', null], 
    ['key 2', 42], 
    ['key 3', 0] 
    ], 
    [ 
    ['key 1', 21], 
    ['key 2', 21], 
    ['key 3', 21] 
    ], 
] 

給孩子們的一組數據...

...我試圖讓父數據看像這樣:

[ 
    [ 
    'key 1', [1, null, 21] 
    ], 
    [ 
    'key 2', [null, 42, 21] 
    ], 
    [ 
    'key 3', [42, 0, 21] 
    ] 
] 

最有可能的,我可以做到這一點使用good'ol for S,但我敢肯定有一個與_.groupBy_.chain_.thru做華而不實的方式。我仍然在努力與_

它那種感覺就像放棄了,問在這裏,但我已經在這一個多一天,試圖找到類似的話,並通過lodash的陣列收集閱讀功能沒有任何結果。

如果你想在jsFiddle上測試它,我已經提取了一小塊實測數據用於測試fiddle

+0

演示數據並不像問題的數據,不清楚什麼預期結果有 – charlietfl

+0

的問題是數據小提琴中的'data'變量的簡化版本,我正在使用的那個調到控制檯,@charlietfl。 –

回答

3

您可以拼合,然後按第1個索引進行分組,然後將這些組映射到預期結果。

var data = [[["key 1",1],["key 2",null],["key 3",42]],[["key 1",null],["key 2",42],["key 3",0]],[["key 1",21],["key 2",21],["key 3",21]]]; 
 

 
var result = _(data) 
 
    .flatten() 
 
    .groupBy(_.head) 
 
    .map(function(v, k) { 
 
    return [k, _.map(v, _.last)]; 
 
    }) 
 
    .value(); 
 
    
 
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

+0

我感覺很傻。我試過這個,但不是用'[0]'分組,而是用'0'分組,並用'1'代替'[1]'。現在我看着它,我不知道我在想什麼。非常感謝。 –

+0

不客氣:) –

+1

除了安德烈Gheorghiu:而不是使用[0]和[1]你可以分別使用'_.head'和'_.last' '.groupBy(_。頭)'。 –

1

使用香草JS:

let data = [[["key 1",1],["key 2",null],["key 3",42]],[["key 1",null],["key 2",42],["key 3",0]],[["key 1",21],["key 2",21],["key 3",21]]]; 
 

 
let tmp =data 
 
    // flatten subarrays 
 
    .reduce((a, c) => a.concat(c), []) 
 
    // create object using 1st index value as keys, array as value 
 
    .reduce((a, c) => { 
 
    a[c[0]] = a[c[0]] || [c[0],[]]; 
 
    a[c[0]][1].push(c[1]); 
 
    return a 
 
    }, {}); 
 
// get all the arrays from object 
 
let res = Object.values(tmp); 
 

 
console.log(res);