2

I have a string:

"id=1&lotcode=ACB&location=A1&id=2&lotcode=CCC&location=B1"

Now I want to get an array of objects to pass to controller via ajax like this:

[{"id":1, "lotcode"="ACB","location":"A1"},{"id":2, "lotcode"="CCC","location":"B1"}]

I started by splitting the string

var string = data.split('&', 2);

now I stuck here...

0

1 Answer 1

2

You could split the string by & and then take the key/value pairs and assign them to an array with an incrementing index.

This solution assumes, that all keys have the same count.

var string = "id=1&lotcode=ACB&location=A1&id=2&lotcode=CCC&location=B1",
    result = [],
    indices = {};

string.split('&').forEach(s => {
    var [key, value] = s.split('='),
        index = (indices[key] || 0);
    
    result[index] = result[index] || {};
    result[index][key] = value;    
    indices[key] = index + 1;
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.