What is the JS equivalent of PHP $$var?

passing javascript variable to php
pass php variable to javascript file
how to convert javascript variable to php variable
how to store javascript value in php variable
how to assign javascript variable to php variable
how to get javascript variable value in php in same page
post javascript variable to php
echo javascript variable in php

I have a form with dynamic fields. I want to format some serialized data before submit. I need to reproduce the PHP $$var in Javascript.

Here is the idea in PHP :

I have this :

$data = array('field1', 0, 'key');
$val = 'somevalue';

And I want this :

$field1[0]['key'] = 'somevalue';

So, here is how I would proceed if I were in PHP (I'm not sure if it would work) :

$data = array('field1', 0, 'key');
$val = 'somevalue';

$field1 = array();
$f = $data[0];           # 'field1'
$i = $data[1];           # 0
$k = $data[2];           # 'key'
$$f[$i][$k] = $val;      # $field1[0]['key'] = 'somevalue';

I saw that we can use window[var] in JS but I don't manage to make it work, I tried this :

var val = 'somevalue';
var field1 = [];
var f = data[0];
var i = data[1];
var k = data[2];

window[f][i] = {};           # field1[0] must be an object
window[f][i][k] = val;       # field1[0] = {'key': 'somevalue'}

As you can see, it's not very simple. Besides, this code is within a foreach because I don't have only one field but a lot of (field2, field3...).

At the end, I have something like :

var result = {
  field1: field1,
  field2: field2,
  ...
  field10: field10
}

// console.log(result);
{
  field1: [
    0 : Object { key: 'somevalue', key2: 'othervalue' }
    ...
    5 : Object { key: 'somevalue2', key2: 'othervalue2' }
  ]
  field2: [...]
  ...
}

EDIT:

Thanks to the answer of @Nina Scholz:

function formatData(object, keys, value) {
    var last = keys.pop();

    keys.reduce((o, k, i, a) =>
        o[k] = o[k] || (isFinite(i + 1 in a ? a[i + 1] : last) ? [] : {}),
        object
    )[last] = value;

    return object;
}

var data = form.serializeArray();
var result = {};

$(data).each(function(i) {
    name = data[i].name;        // field name. Ex: "field1[0][key]"
    value = data[i].value;      // field value

    // Format: "field1[0][key]" => array("field1", "0", "key")
    array = name.split('[');
    array[1] = array[1].replace(']', '');
    array[2] = array[2].replace(']', '');

    // Format every array of data in a big object "result"
    formatData(result, array, value);
});

// JSON encoding of "result" in a hidden field for post-treatment
$('input[name=data]').val(JSON.stringify(result));

You could take the object directly and take a path to the value for setting. This approach checks the key, if that is a number for an array as default value. If an array or object is given, it does not change the data structure.

function setValue(object, keys, value) {
    var last = keys.pop();

    keys.reduce((o, k, i, a) =>
        o[k] = o[k] || (isFinite(i + 1 in a ? a[i + 1] : last) ? [] : {}),
        object
    )[last] = value;

    return object;
}

var val = 'somevalue',
    data = ['field1', 0, 'key'],
    result = {};

setValue(result, data, val);
console.log(result);

Passing PHP Variables to JavaScript, We demonstrate with string, boolean, and numeric values (i.e., scalar values). To pass scalar data held in a PHP variable ( $val ) to a JavaScript variable, place the​  Questions: I would like to see the structure of object in JavaScript (for debugging). Is there anything similar to var_dump in PHP? Answers: Most modern browsers have a console in their developer tools, useful for this sort of debugging. console.log(myvar); Then you will get a nicely mapped out interface of the object/whatever in the console.

You shouldn't create variables dynamically.

let o = {};
o[f][i][k] = val;

writing o.field is not much different from writing just field

To answer your question, you cannot do that in javascript like you can in php. For the record, that counts as poor code also in PHP. In the case of PHP, it prevents the compiler from applying all optimizations.

The function scope is different from the global scope.

This writes the variable bar in the global scope, not in a local scope

var bar = 123; // global bar

(() => {
    var bar; // local bar

    window["bar"] = 456; // this is writing in global "bar", not the local one
})();

console.log(bar);

How to create Javascript variables from PHP variables?, Sometimes, you may need to declare dynamic JS variables using PHP. One thing you can do is to manua Tagged with php, javascript. I'm looking for a JavaScript equivalent of the PHP var_dump() function. When applied to a variable, including an array or object, var_dump() tells us everything PHP knows about the variable, including all its properties, etc.

If you have an array of variable names and you want to create an object where the keys are the variable names and the values are the variable values, this is an example of how you can do that:

var fields = [ 'field1', 'field2', 'field3', 'field4'];

var field1 = 'foo';
var field2 = 'bar';
var field3 = 'baz';
var field4 = 'quux';

var obj = {};

for (var i = 0; i < fields.length; i++) {
    obj[fields[i]] = eval(fields[i]);
}

console.log(obj);

/*
{
  "field1": "foo",
  "field2": "bar",
  "field3": "baz",
  "field4": "quux"
}
*/

Node.js for PHP Developers: Porting PHP to Node.js, After conversion, it still looks very similar, except now it is Node.js code: var x </​body></html> Its Node.js equivalent is very similar to its PHP counterpart, too:  Exchanging variables between JavaScript and PHP. How JavaScript variable are retrieved from PHP script? And conversely, how to use the values of PHP variables in JavaScript? Form's data will be in $_POST or $_GET . Using the content of forms in PHP. Name of elements of a form are also PHP variables as soon as the PHP script is the action of the

Variable variables - Manual, That is, a variable name which can be set and used dynamically. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable​, or if you wanted $$a as the variable and equivalent to this print statement. pure perfection :) thanks for sharing. this is the first try able to print out the "window" object (all other chokes on recursion) @unicornist: try JSON.stringify() the "window" and see the difference

unset - Manual, unset() destroys the specified variables. The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy. var_dump for JavaScript – JavaScript equivalent of PHP var_dump Saturday, 1 August 2015 by Adrian Gordon. Last updated: Saturday, 15 August 2015.

Learning JavaScript from PHP, Variables. Variable Scope. PHP and JavaScript take two very different approaches to declaring variables. In PHP, all variables are local in scope  What is the perfect equivalent of PHP’s isset in JavaScript? In a broader sense, a general, complete guide on JavaScript’s handling of variables that don’t exist, variables without a value, etc. would be convenient.

Comments
  • there is no. but you could use either eval, which is not advisable or an object where you collect all wanted data and access by a key.
  • maybe it is easier to add the form (a small one) and what you like to serialize of it.
  • @NinaScholz data is already the result of form.serializeArray(), I did a foreach on it to format some data in it.
  • @rpaskett Please, read my entire post before answering. I already tested your solution.
  • Possible duplicate of How to use a variable for a key in a JavaScript object literal?
  • Woah thank you very much @Nina ! It's exactly what I wanted to do, works perfectly.
  • I tried eval() too but I don't manage to make it work, could you write me an example that corresponds to my example ahead, please ?
  • Sorry, this answer is wrong. As of ES2015/ES6, you can use a variable as a key in an object literal.
  • and how is that related to what the user was asking? the function scope is not accessible as variable like window is
  • you cannot create a variable with a dynamic name. the only way is eval eval("let " + name + " = " + whatever_serializer(value));