裏面我有一個對象:分配對象索引可用對象
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);
});
有什麼想法又是什麼我缺少什麼埃爾我可以試試嗎?
除了罰款給出的答案,你的解決方案也會起作用。你只需'返回Object.assign(...)'。 'map'將輸入映射到輸出。你沒有返回任何內容,所以'undefined'被隱式地返回給每個鍵。這就是爲什麼你的解決方案給了'[undefined,undefined,undefined]' –