0

Given the following string with key-value pairs, how would you write a generic function to map it to an object?

At the moment, I am just splitting by : and ; to get the relevant data, but it doesn't seem like a clean approach.

This my code at the moment:

var pd = `id:S76519;sku:S76519;name:StarGazer 3000;model:ICC74`;
var tempPd = pd.split(';');
for (i = 1; i < tempPd.length; i++) {
    var b = tempPd[i].split(':');
    console.log(b[1]);
}
4
  • 1
    Well what you're doing is pretty much the only thing you can do. If you've got a string and you want to extract information according to a syntax you expect to find, then you parse the string and build a data structure. Commented Mar 5, 2017 at 18:24
  • 2
    if you know that there are no ; and : in the keys and values then why not? Commented Mar 5, 2017 at 18:25
  • Can you show the code that you're using currently? It's hard to know if there's a more clean approach without seeing what you've already got. Commented Mar 5, 2017 at 18:26
  • @StriplingWarrior this my approach at the moment, as the first two values are identical, i start my increment at 1. Commented Mar 5, 2017 at 18:34

1 Answer 1

1

What about using reduce:

function objectify(str) {

	return str.split(";").reduce(function (obj, item) {
		var a = item.split(":");
		obj[a[0]] = a[1];
		return obj;
	}, {});

}

var strObj = "id:S76519;sku:S76519;name:StarGazer 3000;model:ICC74";
console.log(objectify(strObj));

or:

function objectify(str){

return str.split(";").reduce((obj,item)=>{  
   var a = item.split(":");
   obj[a[0]]=a[1];
   return obj;  
},{});

}
 
var strObj = "id:S76519;sku:S76519;name:StarGazer 3000;model:ICC74";
console.log(objectify(strObj));

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

1 Comment

Works great. Thank you!

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.