0

In JavaScript I have a string like

Package=sdvasd&Qty=1&Price=34?Package=sdabhjds&Qty=1&Price=234?

I want to format that like an object array like this

[
{'Package' : 'sdvasd', 'Qty' : 1, 'Price' : 34 }
{'Package' : 'sdabhjds', 'Qty' : 1, 'Price' : 234 }
]

The code what I have tried so far

let packageData = data.split('?');
let packageArr = [];
if( packageData.length > 0 ) {
  for (var i = 0; i < packageData.length -1; i++) {
    let str = packageData[i].split('&');
    for (var j = 0; j < str.length; j++) {
      let keys = str[j].split('=');
      packageArr.push(keys[1])
    }
  }
}
console.log(packageArr);

But it is not giving me result like this. Can someone tell me how to make this like the desired output. Any suggestions and advice will be really appreciable. I only want javascript method not jQuery

3
  • do you really have more than one question mark in the string? Commented Mar 16, 2018 at 8:46
  • 1
    @Nina Nobody said it's a URL query string… :D Commented Mar 16, 2018 at 8:47
  • @deceze, it was just a friendly remainder ... ;-) Commented Mar 16, 2018 at 8:51

4 Answers 4

1

Use split, map and reduce

var output = str.split("?") //split by ?
   .filter( s => !!s ) //filter out empty 
   .map( s => s.split( "&" ) //split by & and iterate each item
   .reduce( (acc, c) => 
          ( t = c.split("="), acc[t[0]] = t[1], acc) //split each item by = and set each key to accumulator and return the accumulator
   , {}) ); //initialize accumulator

Demo

var str = "Package=sdvasd&Qty=1&Price=34?Package=sdabhjds&Qty=1&Price=234?";
var output = str.split("?") //split by ?
   .filter( s => !!s ) //filter out empty 
   .map( s => s.split( "&" ) //split by & and iterate each item
   .reduce( (acc, c) => 
          ( t = c.split("="), acc[t[0]] = t[1], acc) //split each item by = and set each key to accumulator and return the accumulator
   , {}) ); //initialize accumulator
console.log( output );

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

3 Comments

While nice, this is probably incomprehensible to @NewUser. :)
@deceze I have added more explanation inline.
@gurvinder372 I have a question mark at the end of string. What about that? Package=sdvasd&Qty=1&Price=34?Package=sdabhjds&Qty=1&Price=234?
0

You could split the string and create for the outer splitting an array and for inner splitting the object and for the most inner splitting a key/value pair.

var string = 'Package=sdvasd&Qty=1&Price=34?Package=sdabhjds&Qty=1&Price=234?',
    result = string
        .split('?')
        .filter(Boolean)
        .map(s => s.split('&').reduce((o, p) => {
            var [k, v] = p.split('=');
            return Object.assign(o, { [k]: v });
        }, {}));
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

0

You can use this. Also you can check for number values so that the qty and Price properties has numeric values and not string:

var str = 'Package=sdvasd&Qty=1&Price=34?Package=sdabhjds&Qty=1&Price=234';

var resArray = [];
str.split('?').filter((obj)=>{
  var resObj = {};
  obj.split('&').map((item)=>{
    var itemSplit = item.split('=');
    if(isNaN(itemSplit[1])){
      resObj[itemSplit[0]] = itemSplit[1];
    } else {
      resObj[itemSplit[0]] = parseInt(itemSplit[1]);
    }
  });
  resArray.push(resObj);
});
console.log(resArray);

Comments

0

Try the below code. Create a object and then put the key value pairs.

    let packageArr = [];
let packageDataArr = data.split('?');
Array.prototype.forEach.call(packageDataArr,(packageData)=>{
   let dataObj = {};
   let str = packageData.split('&');
   Array.prototype.forEach.call(str,(keyValue)=>{
      let keys = keyValue.split('=');
      dataObj[key[0]] = key[1];
   });
   packageArr.push(dataObj);
});

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.