A
A
Alex Ershov2015-10-21 16:29:53
PHP
Alex Ershov, 2015-10-21 16:29:53

How to make dynamic multidimensional array in javascript?

But in PHP you can do this:
foreach ($_GET as $item)
$arr[$item['name']][] = $item['value']
How to do this in JS?
The essence of the text: there is an arbitrary number of inputs like these.
I go through each of them with the .each () function and want to make the final array, in which there will be such a hierarchy
arrayName => [
nameOleg => [5,6]
nameIvan=> [5]
]
Objects or arrays it will be all the same. The main thing is that it would be possible to set the names such as they are in the name of the input

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
Daniil Kostin, 2015-10-21
@kilimandjaro

var $arr = {};
if(!$arr[$item['name']]) 
    $arr[$item['name']] = [];
$arr[$item['name']].push($item['value']);

I
Ivanq, 2015-10-21
@Ivanq

var arr = {};
for(var i=0;i<$_GET.length;i++) {
    var item = $_GET[i];
    arr[item.name] = [item.value];
}

H
hjk, 2015-10-21
@hjk

In javascript, everything is very similar. You can do it $arr[$item['name']][] = $item['value'], but instead of square brackets you can use the method push:
Multidimensional dynamic array.

V
Vitaly Inchin ☢, 2015-10-21
@In4in

Array.prototype.reduce.call($("input"), function(p, t){
   return  p[t.name] = t.value, p;
}, {});

----------------------------------------
Example
--------- -------------------------------
<input type="text" name="one" value="222">
<input type="text" name="two" value="228">

And its result
{
   one : "222",
   two : "228"
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question