简体   繁体   中英

Javascript array - how to handle multiple array items with same key/name?

I have a javascript array like this (end result):

Array(
   [text_vars] => Array(
      [0] => 'xxxxxx',
      [1] => 'xxxxxx'
   )
)

Right now the loop I'm using to translate my JSON data into the array:

var aws = json.data;
var text_vars = new Array();

for(i=0; i < 4; i++){
   var id = aws[i]['id'];
   var name = aws[i]['name'];           
   text_vars[i] = id;
}

I then post the resulting array to my PHP processing page, I send them along with my jQuery post in this format:

{ text_vars: text_vars }

I need the array formatted like this:

Array(
   [text_vars][0] => 'xxxxx',
   [text_vars][1] => 'xxxxx'
)

The end goal is to prepare the data so it's ready to be posted via jQuery, like this:

{ text_vars[0]: 'xxxxx', text_vars[1]: 'xxxxx' }

So, if you can suggest a better method to transform the array into that format, I'm happy to hear it :)

var result = {}

for (var i = 0; i < text_vars.length; ++i) {
  result["text_vars[" + i + "]"] = text_vars[i]
}

Now result contains the structure you desire.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM