good day. There is data

data = Array ( [ltype] => Узнать 1 [goal] => uznat_01_now [thanx] => thanx1 [phone] => +7 (111) 222 11 11 [action] => send [formorder] => form-0 ) 

which are sent ajax

  $.ajax({ url:'index.php', type: "POST", data : data, success: function(data){ console.log(data); } }); 

It is necessary to add data from utm tags to the data array

 var utm = new { type_traffic: sbjs.get.current.typ, utm_source: sbjs.get.current.src, utm_medium: sbjs.get.current.mdm, utm_campaign: sbjs.get.current.cmp, utm_content: sbjs.get.current.cnt, utm_term: sbjs.get.current.trm }; 

I needed to add elements to the associative array. There are no associative arrays in JavaScript. Now I can not find an analogue of the function push (). Tell me if anyone knows. Thank.

  • here is a syntax error: var utm = new { , data which comes after all this is an array or an object? - Grundy
  • an associative array is transmitted to the server - Ivan Triumphov

2 answers 2

 let utm = { type_traffic: 'type_traffic', utm_source: 'utm_source', utm_medium: 'utm_medium', utm_campaign: 'utm_campaign', utm_content: 'utm_content', utm_term: 'utm_term', }, data = { // В JS - объекты с именованными ключами НЕ могут быть массивами, так что это объект. PS new не нужен с коротким синтаксисом {} ltype: 'Узнать 1', goal: 'uznat_01_now', thanx: 'thanx1', phone: '+7 (111) 222 11 11', action: 'send', formorder: 'form-0', }; Object.keys(utm).forEach(e => data[e] = utm[e] // Вставляем по ключам // Массив - [1, 2, 3] // Array.prototype.push - отправляет элемент в массив - arr.push('some') ); console.info(data); 

  • Thanks for the answer .... but the data is an example with an error and now I don’t quite understand how to fix it - Ivan Triumphov
  • @IvanTriumphov, the example is working, the object is full. What does not work? PS Perhaps in old browsers the code will not work, for the old ones, the code itself is working. - user207618

The object is an associative array in JavaScript.

A new element can be added to it in two ways: by specifying the key of the element through a dot or in square brackets.

 data.type_traffic = utm.type_traffic // либо const key = 'type_traffic' data[key] = utm.[key] 

The second method is usually used when the value of a variable is required as a key.

In this task, it seems, it will be more convenient not to assign keys one by one, but to merge two objects into one. To do this, you can use the Object.assign method:

 Object.assign(data, utm) 

Alternatively, if you do not need to modify the original data object:

 const result = Object.assign({}, data, utm); 

It should be noted that the method is not supported by all browsers. For better support it is worth connecting a polyfill .