0

I have a string that needs to be converted to an object. But the string has the duplicated items. Since JSON Objects cannot contain 2 items with the same key. The second item is overwriting the first item. How to merge the duplicate items and push to an array?

var string = "test-1=owner&test-1=driver&test-2=Yes&test-3=2&test-4=sun&test-4=moon&test-5=not-agree&test-6=dogs&test-6=testing+js+object&test-7=Testing+js+function&test-7=Testing+js+array"

var stringMod = string.split("&");


var stringObj = {};

stringMod.forEach(function(json) {
  var jsonSplit = json.split("=");

  stringObj[jsonSplit[0]] = [jsonSplit[1]];
});

console.log(stringObj,'stringObj');

Desired output:

{
  "test-1": ["owner","driver"],
  "test-2": ["Yes"],
  "test-3": ["2"],
  "test-4": ["sun","moon"],
  "test-5": ["not-agree"],
  "test-6": ["dogs","testing+js+object"],
  "test-7": ["Testing+js+function","Testing+js+array"]
}

Here is the link to working fiddle: https://jsfiddle.net/sjoh9rqp/

Can you help me how to accomplish this ?

1
  • Using [...(stringObj?.[jsonSplit[0]] || []), jsonSplit[1]]; might work. (It's not pretty though) Commented Jul 21, 2021 at 0:09

3 Answers 3

4

You can use a URLSearchParams to accomplish this, since it treats the string as url parameters it does do decoding though.

var string = "test-1=owner&test-1=driver&test-2=Yes&test-3=2&test-4=sun&test-4=moon&test-5=not-agree&test-6=dogs&test-6=testing+js+object&test-7=Testing+js+function&test-7=Testing+js+array"

var data = new URLSearchParams(string);
var obj = {};
for (let x of data.keys()){
  obj[x] = data.getAll(x);
}
console.log(obj);

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

Comments

3

Using URLSearchParams to parse the query string helps simplify this

var string = "test-1=owner&test-1=driver&test-2=Yes&test-3=2&test-4=sun&test-4=moon&test-5=not-agree&test-6=dogs&test-6=testing+js+object&test-7=Testing+js+function&test-7=Testing+js+array"

const params = new URLSearchParams(string),
      res = {};


params.forEach((v,k)=> { 
  res[k] = res[k] || []
  res[k].push(v);  
})

console.log(res)

Comments

1

For variety, here's the answer solved with reduce(), though I have to admit URLSearchParams is more elegant

var string = "test-1=owner&test-1=driver&test-2=Yes&test-3=2&test-4=sun&test-4=moon&test-5=not-agree&test-6=dogs&test-6=testing+js+object&test-7=Testing+js+function&test-7=Testing+js+array"

let obj = string.split('&').reduce((b,a) => {
  let t = a.split('=');
  if (b.hasOwnProperty(t[0])) b[t[0]].push(t[1]);
  else  b[t[0]] =[t[1]];
  return b;
},{});
console.log(obj)

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.