0
\$\begingroup\$

I have an array of objects that each have a name/value property. The array can contain multiple objects with the same name property. I want to serialize this array into the form:

name:value,value|name:value|name:value,value,value

So basically each property is separated by a | and each value by a ,. The above example is not exactly how I want it to look, just an example of the syntax, results will vary based upon input.

Here is an example of the array:

var objs = [
    {name:"name1", value: "value1"}, 
    {name:"name4", value: "value4"},
    {name:"name3", value: "value3"},
    {name:"name2", value: "value2"},
    {name:"name2", value: "value2"},
    {name:"name2", value: "value3"}
];

I wrote some code to perform this serialization, but I wanted to see if anyone could suggest improvements to this code, I know there are some Javascript experts on this site and wanted to get their opinion:

function serialize(objs){
    var out = "";
    for(var i = 0; i < objs.length; i++){
        var propKey = objs[i].name + ":";

        if (out.indexOf(propKey) == -1){
            out += "|" + propKey; 
        }

        var position = out.indexOf(propKey) + propKey.length;
        out = out.substring(0, position) + objs[i].value + "," + out.substring(position);
    }
    return out.substring(1,out.length-1).replace(/\,\|/g,"|");
}

JS Fiddle: http://jsfiddle.net/BHsuM/

BTW jQuery is acceptable.

\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

Why do you want it serialized specifically in that form? Just use the universal, built-in JSON serialization:

var serialized = JSON.stringify(myvar);
var reconstituted = JSON.parse(serialized);

Done, reconstituted is a normal object again.

\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.