[英]Add a property to a JavaScript object using a variable as the name?
[英]How to add an object property inside an array using a variable name for javascript?
我將如何使用變量名在數組內添加對象屬性?
例如,我有“:
var testArray = [];
var test1 = {
headerTest: results,
test1: test1Results
};
// add to test array
testArray.push(test1);
現在,我需要向testArray [0]添加另一個對象屬性,但要使用變量名。
// I tried these options but not working....
var testProperty = $.trim($('#testProperty').test()); // single word
testArray[0][testProperty] = testResults;
testArray[0].testProperty = testResults;
考慮您的數組和對象:
//array
var testArray = [];
var test1 = {
headerTest: "val1",
test1: "val2"
};
您可以使用jQuery $ .extend函數擴展當前對象test1,並使用您動態創建的另一個對象進行擴展,例如:
var newKey = "someNewKey";
var obj = {};
var newVal = "someValue";
obj[newKey] = newVal;
$.extend(testArray[0], obj);
結果:
[{
headerTest: "val1"
someNewKey: "someValue",
test1: "val2"
}]
您建議的第一種方法應該可以正常工作(如果不是,請檢查您的代碼,例如jQuery核心api中沒有測試方法):
var somethingToAdd = "newKey";
testArray[0][somethingToAdd] = "1";
結果:
[{
headerTest: "val1"
newKey: "1"
test1: "val2"
}]
這個怎么樣:
testArray[0].(testProperty) = testResults;
要么
testArray[0].[testProperty + ''] = testResults;
您首先需要創建一個新對象,因為您無法設置未定義元素的屬性。
testArray[0] = new Object();
testArray[0][testProperty] = testResults;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.