the string is the name of some input fields. Examples:
a[b][c]
x[y][z][]
I'm trying to produce multidimensional arrays from it.
a.b.c = value
x.y.z = [value]
(value is an array because of []
)
anyway i have some ideas on how to do that but first I need to split the string into an array that contains all keys and subkeys.
Searching google I've come up with this
var parts = inputName.match(/[^\[\]]+/g);
it gets me [a,b,c]
, but on the 2nd example I get [x,y,z]
instead of [x,y,z, null]
Any way I can also match []
and add it to the list as null ? I'm not that familiar with regular expressions
@AnnaK. Why can't you simply use ids and keys to send your information? Is it a form that is dynamic in its size? Is it because you're developing a framework that needs to be dynamic? Is it because you're using a function multiple places? Can't you serialize it by using the names? We can't give you suggestions because we still don't know why you need to transfer it as an array (which would be serialized anyway), and we still don't know what your form looks like
Because I'm trying to send the form data with Ajax. Also, before I send the data, I need to prepend a few fields that I create with javascript. I cannot serialize it, at least not with jQuery.serializeArray
if that's what you meant, because if I have multiple keys like x[y][z][]
, only the last one will appear
You can use the following solution:
var parts = inputName.split(/[[\]]{1,2}/);
parts.length--; // the last entry is dummy, need to take it out
console.log(parts); // ["x", "y", "z", ""]
If you need the null value (because there is processing you have no control over for example) you can use this snippet to update the result (curtesy of @Ties):
parts = parts.map(function(item){ return item === '' ? null : item });
Basic idea I had was to look for a [] and than use map()
to replace it with null.
("a[bb][c][]").match(/([^[\]]+|\[\])/g).map( function(val) { return val==="[]" ? null : val; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With