D
D
Dmitry2016-10-11 17:04:02
JavaScript
Dmitry, 2016-10-11 17:04:02

How to add a variable to an array?

Hello!
There is a line:

var meth = "action";
st(meth);
function st(meth){
 data.push({
                   'ecommerce': {
                       meth : { 'products': [product] }
                  }
            });
}

How to make the meth variable correctly added to the array? Now it is written simply meth, instead of action.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Burov, 2016-10-11
@muldy

var value = {
  'ecommerce': {}
};
value.ecommerce[meth] = { 'products': [product] }
 data.push(value);

V
VoidVolker, 2016-10-11
@VoidVolker

var meth = "action", data = [];
function st(meth){
    data.push({
        'ecommerce': {
            [meth]: { 'products': ["product"] }
        }
    });
}
st(meth);

But this syntax is not correct in old JS engines.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question