将字符串转换为javascript对象的最佳方法
我有这个字符串: periodRows.soccer.on:1,periodRows.soccer.periods:1,periodRows.soccer.prematchPeriods=1,periodRows.soccer.label:上半场 将其转换为此对象的最佳方式是什么将字符串转换为javascript对象的最佳方法,javascript,Javascript,我有这个字符串: periodRows.soccer.on:1,periodRows.soccer.periods:1,periodRows.soccer.prematchPeriods=1,periodRows.soccer.label:上半场 将其转换为此对象的最佳方式是什么 periodRows: { soccer: { on: 1, periods: 1, prematchPeriods: 1, label: '1st Half',
periodRows: {
soccer: {
on: 1,
periods: 1,
prematchPeriods: 1,
label: '1st Half',
}
}
请注意,我不控制字符串,因此无法更改它
谢谢改进的递归解决方案
const rec=令牌、索引、目标=>{
const prop=令牌[索引];
如果tokens.length-1==索引{
常量[lastProp,value]=prop.split/[:=]/;
目标[lastProp]=值;
返回目标[lastProp];
}
如果道具&!目标[道具]{
目标[prop]={};
}
返回目标[道具];
}
periodRows.soccer.on:1,periodRows.soccer.periodRows:1,periodRows.soccer.prematchPeriods=1,periodRows.soccer.label:1st Half.split','。ReduceAc,val=>{
常量标记=val.split';
让目标=acc;
对于let i=0;i在功能上,稍微短一点
const f = (obj, keyPath, value) => {
if (keyPath.length === 0) {
return Number.isNaN(Number(value)) ? value : Number(value);
}
const key = keyPath[0];
if (!obj[key]) {
obj[key] = {};
}
obj[key] = f(obj[key], keyPath.slice(1), value);
return obj;
};
const str = "periodRows.soccer.on:1,periodRows.soccer.periods:1,periodRows.soccer.prematchPeriods=1,periodRows.soccer.label:1st Half";
str.split(",")
.map(token => token.split(/[:=]/))
.map(record => ({keyPath: record[0].split("."), value: record[1]}))
.reduce((obj, item) => f(obj, item.keyPath, item.value), {});
上面的字符串格式不正确,转换它的唯一方法是首先将其转换为类似json格式的字符串,类似于以下注意事项类似json的字符串应始终用{}括起来:
var periodRows = '{"soccer":{"on":1,"periods":1,"prematchPeriods":1,"label":"1st Half"}}';
然后您就可以执行转换:
//String to Json
const str = JSON.parse(periodRows);
console.log (str);
//Json to string
var periodRows = {
soccer: {
on: 1,
periods: 1,
prematchPeriods: 1,
label: '1st Half',
}
}
var myStr = JSON.stringify(periodRows);
console.log (myStr);