我正在解析以下对象,我从输入表单字段中获取该对象:
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
我的代码有什么问题吗?
是否有更短的方法来进行此对象解析?
我非常感谢您的回复!
答案 0 :(得分:2)
您可以通过正则表达式匹配您要使用的键的部分:
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 out = {}
for (const key in obj) {
const value = obj[key]
const match = /repeater-group\[([0-9])\]\[([a-z]+)\]/.exec(key)
const index = match[1]
const property = match[2]
out[index] = {...out[index], [property]: value}
}
console.log(out)
/*
{
"1": {
"titel": "test1",
"description": "test1"
},
"3": {
"titel": "test2",
"description": "test2"
},
"5": {
"titel": "test3",
"description": "test3"
}
}
*/
Object.keys(out).forEach(i => console.log(`${out[i].titel}, ${out[i].description}`))
/*
test1, test1
test2, test2
test3, test3
*/