简体   繁体   中英

How to add an object property inside an array using a variable name for javascript?

How would I go about adding an object property inside an array using a variable name?

for example, I have":

var testArray = [];

var test1 = { 
    headerTest: results, 
    test1: test1Results
};
// add to test array
testArray.push(test1);

Now I need to add another object property to testArray[0] but instead using a variable name;

// I tried these options but not working....

var testProperty = $.trim($('#testProperty').test()); // single word

testArray[0][testProperty] = testResults;
testArray[0].testProperty = testResults;

considering your array and object:

 //array 
 var testArray = [];

 var test1 = { 
    headerTest: "val1", 
    test1: "val2"
 };

You can use jQuery $.extend function to extend the current object test1, with another object that you create on the fly, for instance:

 var newKey = "someNewKey";
 var obj = {}; 
 var newVal = "someValue";
 obj[newKey] = newVal; 

 $.extend(testArray[0], obj);

the result:

[{
  headerTest: "val1"
  someNewKey: "someValue",
  test1: "val2"
}]

The first method you propose should work fine(check your code if it's not, for instance there is no test method in jQuery core api):

 var somethingToAdd = "newKey";
 testArray[0][somethingToAdd] = "1";

the result:

[{
  headerTest: "val1"
  newKey: "1"
  test1: "val2"
}]

How about this one:

testArray[0].(testProperty) = testResults;

Or

testArray[0].[testProperty + ''] = testResults;

You'll need to create a new object first because you cannot set the property of an undefined element.

testArray[0] = new Object();
testArray[0][testProperty] = testResults;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM