Darshana Rana
Darshana Rana

Reputation: 145

How can I make dynamic associative array with jquery?

I want array like this:-

arr[0][from] = value
arr[0][to] = value

arr[1][from] = value
arr[1][to] = value

. . And so on.

I have input array html elements for from & to field.

<input type="text" name="from[]" value=""/>
<input type="text" name="to[]" value=""/>

Now, I am making array from below code and it's giving me error in console like "Uncaught TypeError: Cannot read property 'push' of undefined".

    var arr = [];
    $('input[name^=from]').each(function(index,val) {
              var from = $(this).val();
              if(typeof arr[index] === undefined)
                arr[index] = [];

             arr[index].push({from:from});  
    });
    $('input[name^=to]').each(function(index,val) {
              var to= $(this).val();
              if(typeof arr[index] === undefined)
                arr[index] = [];

             arr[index].push({to:to});  
    });

Even if I write arr[index]['from'] = from instead of arr[index].push({from:from}); then also giving error.

Please anybody help me to solve this issue. Thanks in advance.

Upvotes: 0

Views: 2287

Answers (1)

Satpal
Satpal

Reputation: 133403

You need to push if object at index is not defined otherwise update it. You don't need to use typeof

var arr = [];
$('input[name^=from]').each(function(index,val) {
    var from = $(this).val();
    if (arr[index] === undefined) {
        arr[index] = {from: from};
    } else {
        arr[index].from = from;
    }
});
$('input[name^=to]').each(function(index,val) {
    var to= $(this).val();
    if (arr[index] === undefined) {
        arr[index] = {to: to};
    } else {
        arr[index].to = to;
    }
});

var arr = [];
$('input[name^=from]').each(function(index, val) {
  var from = $(this).val();
  if (arr[index] === undefined) {
    arr[index] = {
      from: from
    };
  } else {
    arr[index].from = from;
  }
});
$('input[name^=to]').each(function(index, val) {
  var to = $(this).val();
  if (arr[index] === undefined) {
    arr[index] = {
      to: to
    };
  } else {
    arr[index].to = to;
  }
});

console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="from[]" value="1" />
<input type="text" name="to[]" value="1" />
<input type="text" name="from[]" value="2" />
<input type="text" name="to[]" value="2" />

Upvotes: 2

Related Questions