我有一個要求將數組轉換爲具有鍵值的對象。我試過一些代碼。但沒有得到確切的結果。我可以使用lodash或下劃線js嗎?使用鍵將數組轉換爲ojbect
array = [
{
facebook: 'disneyland',
preview_image_url: 'http: //amt.in/img/amt_logo_big.png'
},
{
preview_image_url: 'http: //amt.in/img/amt_logo_big.png'
twitter: 'disneyland',
},
{
preview_image_url: 'http: //amt.in/img/amt_logo_big.png'
linkedin: 'disneyland',
},
{
xing: 'disneyland',
preview_image_url: ''
},
{
preview_image_url: 'http: //amt.in/img/amt_logo_big.png',
weibo: 'disneyland'
}
]
預期輸出
result = {
facebook: {
facebook: 'disneyland',
preview_image_url: 'http: //amt.in/img/amt_logo_big.png'
},
twitter: {
twitter: 'disneyland',
preview_image_url: 'http: //amt.in/img/amt_logo_big.png'
},
linkedin: {
linkedin: 'disneyland',
preview_image_url: 'http: //amt.in/img/amt_logo_big.png'
},
xing: {
linkedin: 'disneyland',
preview_image_url: 'http: //amt.in/img/amt_logo_big.png'
},
weibo: {
linkedin: 'disneyland',
preview_image_url: 'http: //amt.in/img/amt_logo_big.png'
}
}
我已經試過這
var newnwcontent = {};
array.forEach(function (network) {
var name = Object.keys(network)[0];
newnwcontent[name] = network;
});