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;
}
};
將有助於有關於在何處以及如何被使用和更多的上下文基本的數據結構是什麼 – charlietfl