2015-12-22 34 views
0

我目前正在操作數組/對象中的項目。我之前並沒有與lodash一起工作過,但是在閱讀了這個實用工具提供的多少功能之後,我決定放棄它。我想修改的數組涉及添加一個附加對象sources並更改密鑰。我如何使用lodash實現以下目標?操作和更改原始數組的鍵

當前陣列

var myArr = 
[{ 
    "flv": "myFile.flvs", 
    "mp4": "myFile.mp4", 
    "webm": "myFile.webm", 
    "thumbnail": "poster.png", 
    "title": "Test", 
    "id": 123456 
}]; 

期望的結果

{ 
data: [ 
    { 
     sources: [{ 
      file: "myFile.flv" 
     },{ 
      file: "myFile.mp4" 
     },{ 
      file: "myFile.webm" 
     }], 
     image: 'poster.png', 
     title: 'Test', 
     id: '123456' 
    }, 
    .... 
    ] 
} 
+0

確實有三個'testn'屬性,或任意數字嗎?無論如何,你只需要編寫一個'transform'函數,然後執行'myArr.data = _.map(myArr.data,transform)',對於'transform',我建議用英文寫下你想要做的變換,或者僞代碼,然後它應該直接將其轉化爲代碼。 – 2015-12-22 04:38:11

+0

@torazaburo它的任意數字 –

回答

2

如何:

var myArr = { 
    "data": [{ 
     "test1": "myFile.flv", 
     "test2": "myFile.mp4", 
     "test3": "myFile.webm", 
     "thumbnail": "poster.png", 
     "title": "Test", 
     "id": 123456 
    }] 
}; 

var result = _.map(myArr.data, function(el) { 
    var sources = [] 
    _.each(el, function(v, k) { 
     if (k.match(/test\d*/) !== null) { 
      sources.push({ 
       file: v 
      }); 
     } 
    }); 
    return { 
     sources: sources, 
     image: el.thumbnail, 
     title: el.title, 
     id: el.id 
    }; 
}); 

console.log(result); 

結果:

enter image description here

每個操作請求

更新:

var EXTENSIONS = ['flv', 'mp4', 'webm']; 
var myArr = [{ 
     "flv": "myFile.flv", 
     "mp4": "myFile.mp4", 
     "webm": "myFile.webm", 
     "thumbnail": "poster.png", 
     "title": "Test", 
     "id": 123456 
    }]; 

var result = _.map(myArr, function(el) { 
    var sources = []; 
    _.each(el, function(v, k) { 
     if (_.contains(EXTENSIONS, k)) { 
      sources.push({ 
       file: v 
      }); 
     } 
    }); 
    return { 
     sources: sources, 
     image: el.thumbnail, 
     title: el.title, 
     id: el.id 
    }; 
}); 

console.log(result); 

注:這裏我們可以使用_.contains(這是lodash)或EXTENSIONS.indexOf(它的JavaScript本機)。既然你想學習lodash,我想我們使用_.contains。

更新:剛從地圖函數中刪除.data,因爲OP從源數據中刪除數據屬性。

+0

我做了一個修改,而不是具有'testn'鍵的數組,鍵是'flv','mp4'和'webm'。 –

+0

@Code_Ed_Student - 我看到更新,你有答案,或者你還需要一些幫助嗎? – Will

+0

是的,請你說明如何使用不同的鍵來做到這一點。 –