2014-10-27 55 views
0

這只是邏輯問題,如果我有數據:的CoffeeScript - 操縱JSON

[ 
     { 
      from: 'user a', 
      to: 'user b' 
     }, 
     { 
      from: 'user a', 
      to: 'user c' 
     }, 
     { 
      from: 'user b', 
      to: 'user d' 
     }, 
     { 
      from: 'user c', 
      to: 'user d' 
     }, 
     { 
      from: 'user c', 
      to: 'user d' 
     } 
    ] 

,我需要的數據操縱到:

[ 
     { 
      from: 'user a', 
      to: ['user b', 'user c'] 
     }, 
     { 
      from: 'user b', 
      to: ['user d'] 
     }, 
     { 
      from: 'user c', 
      to: ['user d'] 
     } 
    ] 

我用這個代碼:

result = [] 
    objTemp = obj 
    from = []  
    obj.map (o) -> 
     if o.from not in from 
      from.push o.from 
      to = [] 
      objTemp.map (oo) -> 
       if oo.from is o.from and oo.to not in to 
        to.push oo.to 
      temp = 
       from: o.from 
       to: to 
      result.push temp 

但結果不是我所期望的,在'from'中仍然存在'to':

[ 
     { 
      from: 'user a', 
      to: ['user b', 'user c'] 
     }, 
     { 
      from: 'user b', 
      to: ['user d'] 
     }, 
     { 
      from: 'user c', 
      to: ['user d', 'user d'] <-- the problem 
     } 
    ] 

你們如何使用coffeescript解決它?

回答

0

這裏是我會怎麼做:

res = [] 
obj.map (o) -> 
    for r in res when r.from is o.from 
    return (r.to.push o.to unless o.to in r.to) 
    res.push from: o.from, to: [o.to] 
+0

當你必須在map函數外聲明一個數組時,你知道你使用的map錯誤。我可以建議減少嗎? http://jsfiddle.net/eaL6t1cn/ – 2014-10-28 16:35:26

+0

@JedSchneider,我相信你是對的。但是你的小提琴有一個小問題,它會返回重複的條目。如果我嘗試在'for'循環中'返回',它會拋出一個錯誤。你如何處理這個問題? – mutil 2014-10-28 16:59:53

+0

對不起@multi我沒有調試的準確性,只是告訴你如何通過數組來減少使用你的方法。我可以更深入地觀察並提供答案。我沒有意識到這是造成不準確的結果。 – 2014-10-28 17:24:37

0

爲具有groupByuniq方法的便利性(以及chain,我猜),我可能會使用下劃線或lowdash。如果你對它們的實現感興趣,以便在原始咖啡文本中完成,你可以看看註釋的源代碼。

http://underscorejs.org/docs/underscore.html

chain/value只是讓我把這些內聯,而不是使臨時變量來保存它們或使函數調用不太明顯。

fromUser = (x)-> x.from 

toRelationships = (memo, items, index, list)-> 
    key = _(items).pluck('from')[0] 
    vals = _.values(list[key]) 
    memo[key] = _(vals).chain().pluck('to').uniq().value() 
    memo 

result = _(data).chain().groupBy(fromUser).reduce(toRelationships, []).value() 

# without chain 
grouped = _(data).groupBy(fromUser) 
result = _(grouped).reduce(toRelationships, []) 

的jsfiddle:http://jsfiddle.net/eaL6t1cn/2/

0

這是我拿的,我現在道歉這不是簡明扼要我希望。如果我使用jQuery(或其他第三方),這會更簡單一些,但這裏沒有任何庫。

a =  [ 
     { 
      from: 'user a', 
      to: 'user b' 
     }, 
     { 
      from: 'user a', 
      to: 'user c' 
     }, 
     { 
      from: 'user b', 
      to: 'user d' 
     }, 
     { 
      from: 'user c', 
      to: 'user d' 
     }, 
     { 
      from: 'user c', 
      to: 'user d' 
     } 
    ] 
c = {} 
d = [] 
(value for value in a).forEach (v) -> 
    c[v.from] = do -> if not c[v.from] then [v.to] else ("#{c[v.from]},#{v.to}"). 
     split(',').reduce ((p,c) -> 
      if c not in p then p.concat([c]) else [c]), [] 

d.push {'from':v,'to':k} for v,k of c 

console.log d