2016-01-21 44 views
0

DEV TOOLS角1.4.8/lodash解析對象的數組使用條件參數

  • 角1.4.8,lodash 4.0

最終溶液

建築斷Derek的代碼貢獻如下。不得不調整爲_.property()或_.map()與_.find鏈產生解析不確定時異常:

  var getProfileImage = function(images) { 
       var defaultPath = 'images/profile/darthvader.jpg'; 
       if(!images || !images.length) return defaultPath; 

       if (images) { 
        thumbnail = _.find(images, {type: 10}); 
        return thumbnail ? _.has(thumbnail, 'data_url') ? thumbnail.data_url : defaultPath: defaultPath; 
       } 
      }, 

目的

我敢肯定,這是一個小白問題,因爲我是新來的JS,並提前道歉,如果它明顯。以下是解析圖像以查找配置文件圖像的方法。如果圖像存在,則提取'data_url'屬性。如果圖像或圖像類型可能不存在,請使用通用路徑替換。注意這個方法有效,但看起來很冗長。

問題

使用上述工具是有一個更簡潔的方式來達到同樣的效果?

(阿里納斯)我已經嘗試使用lodash chain()_.pluck()一起,但我不斷收到一個類型的錯誤,我懷疑是結果,如果發現或過濾器會返回一個未定義

TypeError: chain() ..._.pluck is not a function

數據例子(簡化):

$images = [ 
{id: 1, 
type: 10, 
data_url: base64string 
}, 
{id: 2, 
type: 11, // note: not equal 
data_url: base64string 
} 
]; 
以上 方法提到

方法是從指令模板調用下面的代碼。爲簡潔起見移除了指令代碼:

"<img class='thumbnail__image' ng-src='{[{conversation.getImage(comment.profile.images)}]}'/>, 

方法

var getProfileImage = function(images) { 
     var thumbnail = null; 
     var path = 'images/profile/generic-thumbnail.png'; 

     if (images) { 
      thumbnail = _.find(images, function(image) { 
       return image.type === 10; 
      }); 
      if (_.isUndefined(thumbnail)) { 
       thumbnail = path; 
      } else if (_.has(thumbnail, 'data_url')) { 
       thumbnail = thumbnail.data_url'; 
      } 
      return thumbnail; 
     } 
    }; 
+0

將有助於有關於在何處以及如何被使用和更多的上下文基本的數據結構是什麼 – charlietfl

回答

3

這個問題會更適合https://codereview.stackexchange.com/

但這裏是你如何能清理你的代碼的例子:

var getProfileImage = function(images) { 
    var defaultPath = 'images/profile/generic-thumbnail.png'; 

    if(!images || !images.length) return defaultPath; 

    var thumbnailPath = _(images) 
     .find({ type: 10 }) 
     .map('data_url') 
     .value(); 

    return thumbnailPath ? thumbnailPath : defaultPath; 
}; 
1

_.pluck肯定會令你的代碼更簡潔,但它已經從lodash4.0.0刪除:lodash 4.0.0 changelog

您現在可以使用_.map代替_.pluck