简体   繁体   中英

Mapping string with key-value pair to object

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]);
}

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)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM