2017-10-28 132 views
1

裏面我有一個對象:分配對象索引可用對象

var contacts = 
{ 
    'KxN5RVjE1zoGqrzYKOV' : 
    {email: "[email protected]", firstName: "Lora", lastName: "Did"}, 

    '-KxN7AkNyiVjMYReZzbQ': 
    {email: "[email protected]", firstName: "Tom", lastName: "Smith"}, 

    '-KxN743hpoTVWIqR75XD': 
    {email: "[email protected]", firstName: "Polina", lastName: "Polina"} 

}; 

我需要它的鍵是一個數值,所以它看起來就像這樣:

var contacts = 
{ 
    'KxN5RVjE1zoGqrzYKOV' : 
    {email: "[email protected]", firstName: "Lora", lastName: "Did", id:'KxN5RVjE1zoGqrzYKOV'}, 

    '-KxN7AkNyiVjMYReZzbQ': 
    {email: "[email protected]", firstName: "Tom", lastName: "Smith", id: '-KxN7AkNyiVjMYReZzbQ'}, 

    '-KxN743hpoTVWIqR75XD': 
    {email: "[email protected]", firstName: "Polina", lastName: "Polina", id:'-KxN743hpoTVWIqR75XD'} 

}; 

這是代碼我到目前爲止,不添加任何東西,只是安慰同樣的老對象:

var results = Object.keys(contacts).map((key, id) => { 
    var contact = contacts[key]; 
    Object.assign({}, contact, {id: key}); 
    console.log(contact); 
}); 

有什麼想法又是什麼我缺少什麼埃爾我可以試試嗎?

+0

除了罰款給出的答案,你的解決方案也會起作用。你只需'返回Object.assign(...)'。 'map'將輸入映射到輸出。你沒有返回任何內容,所以'undefined'被隱式地返回給每個鍵。這就是爲什麼你的解決方案給了'[undefined,undefined,undefined]' –

回答

1

如果你想創建一個新的對象而不是修改,你可以試試reduce -

var results = Object 
    .keys(contacts) 
    .reduce((newObj, key) => Object.assign(
     newObj, 
     {[key]: Object.assign({id: key}, contacts[key])} 
    ), {}) 
+0

謝謝!我非常喜歡你的解決方案! – Polina

3

如果你不介意修改原始對象,你可以使用forEach遍歷鍵,並添加id每個元素:

var contacts = 
 
{ 
 
    'KxN5RVjE1zoGqrzYKOV' : 
 
    {email: "[email protected]", firstName: "Lora", lastName: "Did"}, 
 

 
    '-KxN7AkNyiVjMYReZzbQ': 
 
    {email: "[email protected]", firstName: "Tom", lastName: "Smith"}, 
 

 
    '-KxN743hpoTVWIqR75XD': 
 
    {email: "[email protected]", firstName: "Polina", lastName: "Polina"} 
 

 
}; 
 

 
Object.keys(contacts).forEach(key => { 
 
    contacts[key]['id'] = key; 
 
}); 
 

 
console.log(contacts);

+0

OMG你已經解決了這麼快! – Polina