2016-03-08 26 views
0

我使用Object.assign從另一個映射中獲取具有添加屬性的對象的新副本。這通常與Object.assign(existingObject,{「new_key」,「new_value」})一樣簡單,但是當「new_key」以變量的形式出現時,我必須使用一個臨時變量。如何避免這種情況?使用變量作爲Object提供給Object.assign的鍵

一個簡單的例子:

function demo(inputKey, inputValue) { 
    let data = { 
     "existing_key": "existing_value" 
    } 
    let newData = {} 
    newData[inputKey] = inputValue 
    return Object.assign(data, newData) 
} 
//demo("new_key", "new_value") 
//returns Object {existing_key: "existing_value", new_key: "new_value"} 

如何避免臨時newData變什麼花樣,將不勝感激!

(我的工作很多,在終極版,爲複製對象,而不是突變,他們這個有很大的使用減速器。)

+0

我想有一個捷徑。如果包含值和鍵名稱的變量名稱相同,則它接受它。例如:'var a =「1」,b =「2」; var c = {a,b}'output:'{a:「1」,b:「2」}'。 [MDN參考](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) – Rajesh

回答

0

您可以ES2015使用computed property names做到這一點:

return Object.assign(data, {[inputKey]: inputValue}) 
0

您可以強制如果你用方括號括起來的變量被用作對象文本的關鍵:

function demo(inputKey, inputValue) { 
 
    let data = { 
 
     "existing_key": "existing_value" 
 
    } 
 
    let newData = {[inputKey] : inputValue} 
 
    //newData[inputKey] = inputValue 
 
    return Object.assign(data, newData) 
 
} 
 

 

 
console.log(demo('one',42))

0

您已經創建了一個新對象數據,無需再創建另一個對象。

function demo(inputKey, inputValue) { 
    let data = { 
     "existing_key": "existing_value" 
    } 

    data[inputKey] = inputValue; 

    return data; 
} 
相關問題