2014-09-11 52 views
-1

如果我有一個現有的POJO,並希望一些鍵/值對添加到它,我通常做它像這樣:簡單地將許多鍵/值對添加到現有JavaScript對象?

var existingObject = { 
    firstValue: 'hello' 
}; 

/* some time later... */ 

existingObject.secondValue = 'world'; 
existingObject.thirdValue = 'new value'; 
existingObject.fourthValue = 'another value'; 
existingObject.fifthValue = 'another value'; 
existingObject.sixthValue = 'another value'; 
existingObject.seventhValue = 'another value'; 
existingObject.eighthValue = 'another value'; 
existingObject.adInfinitum = 'again and again...'; 

但我不知道是否有比這longhanded方法更有效的方法?但請注意,我正在尋找創建臨時對象的替代方法,並致電extend

此外,簡單地將對象存儲在一個較小的變量(如var a = existingObject;和使用a.newValue = 'something')不是我正在尋找的解決方案。

有沒有辦法做到這一點?

+1

請詳細說明。價值從何而來?哪一部分可以製作DRYer? – 2014-09-11 01:18:19

+1

我假設你不能簡單地將它們全部添加到實例化中,就像你做了firstValue一樣?你正在具體談論實例化之後添加額外的值嗎? – kman 2014-09-11 01:20:05

+0

你如何使用一個數組:'existingObject.values = [「hello」,「world」,「new value」,「another value」,「again and again ......」]等等。 – soktinpk 2014-09-11 01:25:35

回答

4

隨着新的ES6方法Object.assign,大部分重複的樣板可以消除。例如:

var existingObject = { 
    firstValue: 'hello' 
}; 

/* some time later... */ 

Object.assign(existingObject, { 
    secondValue: 'world', 
    thirdValue: 'new value', 
    fourthValue: 'another value', 
    fifthValue: 'another value', 
    sixthValue: 'another value', 
    seventhValue: 'another value', 
    eighthValue: 'another value', 
    adInfinitum: 'again and again...' 
}); 
// existingObject now has all these properties 

這將做到這一點,而不使用其他臨時變量或調用一些外部extend方法。

3

簡答:沒有。

或者,我可以建議的最好的方法是採用可變參數,在鍵和值之間交替的函數。只需將其作爲一個裸函數,可以選擇將現有對象擴展。

1

思考這個問題後,我想出了這個可能的解決方案:

Object.prototype.val = function(key, value) { 
    this[key] = value; 
    return this; 
}; 

var existingObject = { 
    firstValue: 'hello' 
}; 

existingObject 
    .val('secondValue', 'world') 
    .val('thirdValue', 'new value') 
    .val('fourthValue', 'another value') 
    .val('adInfinitum', 'again and again...'); 

雖然有能夠做出有關仍需要進行通話按鍵次數,以較小的變量名的說法,等它可能是值得的。

+1

我真的不明白這是如何提供任何好處。 – 2014-09-11 02:16:24

+0

事實上它可能不是。但如果有人有更好的想法,請讓我知道! – Bryce 2014-09-11 02:18:26

相關問題