2016-08-05 82 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')