-2

I know how to loop through array to get value... but I don't know how to use it to assign data name in ajax. is it possible to do this?

<script>
    var my_array = ["orange", "apple", "banana"];

    $.post(url, {
    orange: 'orange',     //I want to use value in array to define data name in ajax
    apple: 'apple',
    banana : 'banana' 
    }, function (data) {

                alert("Success Post Data!");
                });
            });

/////// so I want something like this

    $.post(url, {
    my_arr[0]: 'my_arr[0]',    
    my_arr[1]: 'my_arr[1]',
    my_arr[2] : 'my_arr[2]',
    .......................
    my_arr[n] :  'my_arr[n] 
    }, function (data) {

                alert("Success Post Data!");
                });
            });

but don't know how to do it. How could I do?

doflamingo
  • 567
  • 5
  • 23
  • It's not at all clear what you're asking. Are you asking [this](http://stackoverflow.com/questions/695050/how-do-i-add-a-property-to-a-javascript-object-using-a-variable-as-the-name)? – T.J. Crowder May 04 '17 at 21:48
  • Don't undo constructive edits. Tags don't go in titles. We have tags for that. – T.J. Crowder May 04 '17 at 21:49
  • **Again:** Are you asking [this](http://stackoverflow.com/questions/695050/how-do-i-add-a-property-to-a-javascript-object-using-a-variable-as-the-name)? – T.J. Crowder May 04 '17 at 21:56

2 Answers2

1

Create a object first and the post what i understand u want the value of ur array as key

var postObject = {};
postObject[my_arr[0]] = 'my_arr[0]';
...
postObject[my_arr[n]] = 'my_arr[n]';

then post that object

$.post(url, postObject, function (data) {

                alert("Success Post Data!");
                });
            });
mastermind
  • 1,057
  • 1
  • 8
  • 15
  • 1
    We don't need yet another answer to [this question](http://stackoverflow.com/questions/695050/how-do-i-add-a-property-to-a-javascript-object-using-a-variable-as-the-name). – T.J. Crowder May 04 '17 at 22:00
0

yes, its possible:

var my_array = ["orange", "apple", "banana"];
var dataToSend = {};
my_array.forEach(function(d){
   dataToSend[d] = d;
});
$.post(url, dataToSend, function (data) {
      alert("Success Post Data!");
    });
});
  • We don't need yet another answer to [this question](http://stackoverflow.com/questions/695050/how-do-i-add-a-property-to-a-javascript-object-using-a-variable-as-the-name). – T.J. Crowder May 04 '17 at 22:00