Home › Forums › JavaScript › serialize 2 dimensional array
- This topic is empty.
-
AuthorPosts
-
November 16, 2016 at 8:17 am #247922
triplebit
ParticipantI have an array like as follows:
var a = [
[“val1”, “val2”, “val3”],
[“val4”, “val5”, “val6”,
[“val9”, “val8”, “val7″]
];
I want to serialize it so that I can set it as a value of a text box with id=input-id as follows:<input id=”input-id” type=”text” name=”serialization_stack” value=””/>
serialized_a = serialize_array(a);
$(‘#input-id’).val(serialized_a);
Can someone help me to define the function serialize_array()?
ThxNovember 16, 2016 at 9:46 am #247925Shikkediel
ParticipantSomething like this?
November 16, 2016 at 10:00 am #247926Alex Zaworski
ParticipantIt’s possible I’m misunderstanding the question (based on Shikkediel’s repsonse) but can’t you just use
JSON.stringify()
here? MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringifyNovember 16, 2016 at 10:52 am #247928Shikkediel
ParticipantI’m not so sure either but it turns out to be quite an interesting question, going into the possibilities of JS methods. This one’s pretty neat too:
var result = a.map(function(it) { return it.join('&'); }); result = result.join('&');
So with the first step and
.map
a single new array is created while looping over each element (it
), looking like this:['val1&val2&val3','val3&val4&val5','val9&val8&val7']
Then that array is also turned into a string with
join
, using&
as the separator character:'val1&val2&val3&val4&val5&val6&val9&val8&val7'
November 16, 2016 at 12:03 pm #247931Shikkediel
ParticipantOr this way…
var result = ''; a.forEach(function(it) { result += it.join('&'); });
If I understood that to be intended with “serialization” correctly.
The
JSON.stringify()
approach was interesting as well but I stumbled upon the brackets, quotes and commas being quite circumventive to get removed from the string value.November 16, 2016 at 2:18 pm #247933Alex Zaworski
ParticipantYou’d need some way to reconstruct the array without losing the dimensionality though— you can’t do that if you just concatenate everything.
November 16, 2016 at 2:39 pm #247934Shikkediel
ParticipantOn the basis of the question I was assuming only serialisation of all the containing elements was needed. If it should be deserialised including inner structure again,
JSON.stringify
andJSON.parse
would of course be more appropriate.November 17, 2016 at 12:27 am #247939triplebit
ParticipantThx all
I tried JSON.stringify and it seems to be fine.
Regards -
AuthorPosts
- The forum ‘JavaScript’ is closed to new topics and replies.