0

Update note: I believe this is different from the linked "duplicate" answer because I'm not asking how to use a variable name as the "name" (since I've shown I know how to do that), but rather, how to achieve the intended result below.

I currently have the custom data layer variable as an array that is populated in the following notation:

myArray.push({"name":"value"});

That said, the expected output should be like so:

[{"name1":"value1", "name2":"value2", "name3":"value3"}]

Now my current dilemma is that I need to add another item in the array, however, my "name" is stored in a variable.

Using the variable name leads to the variable name being used as the "name", so that won't work.

myArray.push({varName:"value"});

Results in:

[{"varName":"value"}]

I've also tried creating a new object, and inserting that in, but that just adds the object into the array without the correct "name".

var myObject = {};
myObject[varName] = "value";

myArray.push(myObject);

Results in:

[{"Message": {"varName":"value"}}]

Now, I'm out of ideas on how to go about with this, so any help is much appreciated!

TIA

Hatdog
  • 296
  • 2
  • 8

2 Answers2

0

If you can use ECMAScript 2015 you can do with computed property names:

myArray.push({[varName]:"value"});
madox2
  • 49,493
  • 17
  • 99
  • 99
0

I couldn't understand your question if you wanted to delete the variable "name" inside myArray or update it?

For adding new variables inside myArray just do another .push for name

myArray.push = [{
'name': 'value',
'name1': 'value',
'name2': 'value',
'name3': 'value',
}];

For removing the variable name this code would do it for more information about flushing variable read this Simo Ahava's blog http://www.simoahava.com/gtm-tips/remember-to-flush-unused-data-layer-variables/

myArray.push = [{

'name': undefined,
'name1': 'value',
'name2': 'value',
'name3': 'value',

}];
sky
  • 151
  • 10