给定以下带键值对的字符串,如何编写通用函数将其映射到对象?
目前,我只是按getExerciseDescription(exerciseId, intensity_level){
alert(exerciseId + " " + intensity_level)
switch (exerciseId && intensity_level) {
case (1 && 1):
this.header="Exercise 1 Level 1";
this.instructions="Exercise 1 Level 1";
break;
case (1 && 2):
this.header="Exercise 1 Level 2";
this.instructions="Exercise 1 Level 2";
break;
case (2 && 1):
this.header="Exercise 2 Level 1";
this.instructions="Exercise 2 Level 1";
break;
case (2 && 2):
this.header="Exercise 2 Level 2";
this.instructions="Exercise 2 Level 2";
break;
default:
this.header="Default";
this.instructions="Default";
break;
}
return new Popup(this.header, this.instructions);
}
和:
进行拆分以获取相关数据,但这似乎不是一种干净的方法。
此刻我的代码:
;
答案 0 :(得分:1)
使用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));

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