2015-06-06 72 views
0

我有一個要求將數組轉換爲具有鍵值的對象。我試過一些代碼。但沒有得到確切的結果。我可以使用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; 
          }); 

回答

2

您需要檢查屬性鍵索引0不能保證

var newnwcontent = {} 

array.forEach(function(el) { 
    var keys = Object.keys(el) 
    var key = keys[0] == 'preview_image_url' ? keys[1] : keys[0] 
    newnwcontent[key] = el 
}) 
0

可以使用這樣的功能來獲得您需要的結果:

var result = {}; 
// iterate through all networks 
array.forEach(function (network) { 
    // iterate through all properties of an array item 
    for(var property in network){ 
     // ignore property preview_image_url 
     if(property!=='preview_image_url') 
     { 
      // any other property is your key, add an item to result object 
      result[property] = network; 
     } 
    } 
}); 
// output the result 
console.log(result); 
2

您可以用下面的辦法在lodash:

_.indexBy(array, function(item) { 
    return _(item) 
     .keys() 
     .without('preview_image_url') 
     .first(); 
}); 

這裏,indexBy()返回基於陣列中的新對象。你傳遞它的函數告訴它如何構造密鑰。在這種情況下,您使用keys()獲取密鑰,without()刪除不需要的內容,並使用first()獲取該值。