2016-08-05 84 views
0

有人可以看看這個,並有意義如何把它變成本地的JS。下劃線的方法ES6

_.chain(polls).deepClone().indexBy("id").value() 

我試圖查找deepClone,無法找出它從何而來。這是我接管的代碼,並不太熟悉它。感謝幫助。

這裏是一個工作示例,我有:

function loadPolls() { 
    return ScheduledEventService.getPolls($scope.webcastId) 
     .then(function(polls){ 
      $scope.originalPolls = _.chain(polls).deepClone().indexBy("id").value(); 
      $scope.webcast.polls = polls; 

      _.each(polls, function(poll){ 
       poll.answers = _.map(_.range(Polls.MaxAnswers), function(i){ 
        return (poll.answers && poll.answers[i]) || {}; 
       }); 

       poll.readOnly = poll.status !== "Closed" || poll.totalResponses > 0; 
      }); 
     }); 
} 
+0

哎喲-1。原因呢? – pertrai1

+1

你能提供工作示例嗎? –

+0

@PratikParekh - 我希望我所添加的幫助 – pertrai1

回答

1

既不deepClone也不indexBy(來自下劃線)有直接的天然等同物。

indexBy是很容易的:

function indexBy(object, key) { 
    return Object.keys(object).reduce(result, k) { 
    const value = object[k]; 
    result[value[key]] = value; 
    return result; 
    }); 
} 

它使用reduce通過輸入對象(實際上,走過它的鍵)行走,並建立一個result對象,它的鍵是id財產上的值每個子對象,其值都是子對象本身,就像_.indexBy一樣。

deepClone你將不得不尋找一些版本。在這裏有很多。

一旦你擁有了這些,你的邏輯很簡單

indexBy(deepClone(polls), 'id') 

如果只需要一個級別深克隆的,你可以改變上面

result[value[key]] = Object.assign({}, value); 

,然後就做

indexBy(polls, 'id')