Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript serialize 2 dimensional array

  • This topic is empty.
Viewing 8 posts - 1 through 8 (of 8 total)
  • Author
    Posts
  • #247922
    triplebit
    Participant

    I 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()?
    Thx

    #247925
    Shikkediel
    Participant

    Something like this?

    Link

    #247926
    Alex Zaworski
    Participant

    It’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/stringify

    #247928
    Shikkediel
    Participant

    I’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:

    Demo

    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 &amp; as the separator character:

    'val1&val2&val3&val4&val5&val6&val9&val8&val7'
    
    #247931
    Shikkediel
    Participant

    Or this way…

    With forEach()

    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.

    codepen.io/anon/pen/ENgOOV

    #247933
    Alex Zaworski
    Participant

    You’d need some way to reconstruct the array without losing the dimensionality though— you can’t do that if you just concatenate everything.

    #247934
    Shikkediel
    Participant

    On 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 and JSON.parse would of course be more appropriate.

    #247939
    triplebit
    Participant

    Thx all
    I tried JSON.stringify and it seems to be fine.
    Regards

Viewing 8 posts - 1 through 8 (of 8 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.