Javascript 分析同一索引上有多个键的对象
我正在努力解析从输入表单字段获得的以下对象:Javascript 分析同一索引上有多个键的对象,javascript,Javascript,我正在努力解析从输入表单字段获得的以下对象: const obj = { 'repeater-group[1][titel]': 'test1', 'repeater-group[1][description]': 'test1', 'repeater-group[3][titel]': 'test2', 'repeater-group[3][description]': 'test2', 'repeater-group[5][titel]': 'test3', 'repea
const obj = { 'repeater-group[1][titel]': 'test1',
'repeater-group[1][description]': 'test1',
'repeater-group[3][titel]': 'test2',
'repeater-group[3][description]': 'test2',
'repeater-group[5][titel]': 'test3',
'repeater-group[5][description]': 'test3' }
const desc = 'undefined'
const titel = 'undefined'
let i = 0
for (const k in obj) {
const item = obj[k]
if (k === `repeater-group[${i}][titel]`) {
titel = item
}
if (k === `repeater-group[${i}][description]`) {
desc = item
}
if (titel != 'undefined' && desc != 'undefined') {
try {
console.log(titel + ", " + desc)
}
catch (error) {
console.log(error)
}
}
i += 1
}
// Currently there is no output
我想有以下输出
//Expected output
// test1, test1
// test2, test2
// test3, test3
有什么建议我的代码有什么问题吗
是否有一种更短的方法来进行对象解析
非常感谢您的回复 您可以通过正则表达式匹配要使用的密钥部分:
const obj={
“中继组[1][titel]”:“test1”,
'中继器组[1][description]':'test1',
“中继器组[3][titel]”:“测试2”,
'中继器组[3][description]':'test2',
“转发器组[5][titel]”:“test3”,
“中继器组[5][说明]”:“test3”
}
常数out={}
用于(obj中的常量键){
常量值=对象[key]
常量匹配=/中继器组\[([0-9])\]\[([a-z]+)\]/.exec(键)
常数索引=匹配[1]
常量属性=匹配[2]
out[index]={…out[index],[property]:value}
}
console.log(注销)
/*
{
"1": {
“滴度”:“测试1”,
“说明”:“测试1”
},
"3": {
“滴度”:“测试2”,
“说明”:“测试2”
},
"5": {
“滴度”:“测试3”,
“说明”:“test3”
}
}
*/
Object.keys(out).forEach(i=>console.log(`${out[i].titel},${out[i].description}`)
/*
测试一,测试一
测试2,测试2
测试3,测试3
*/
titel
和desc
是常量,您正在尝试分配给它们。您需要使它们成为变量。@obsidiange我将变量更改为let
。我仍然没有得到任何输出。这是因为您的两个变量都是未定义的,因此您的逻辑永远不会进入条件。如果将else
链接到If(titel!=“undefined”&&desc!=“undefined”)
逻辑将输入它。