i receive this entrie from form html POST request
const obj = {
'experience[0].companyName': 'test',
'experience[0].postName': 'testt',
'experience[0].startDate': '2022-01-04',
'experience[0].endDate': '',
'experience[0].description': '',
'experience[1].companyName': 'stet',
'experience[1].postName': 'esttest',
'experience[1].startDate': '',
'experience[1].endDate': '',
'experience[1].description': 'stetset'
}
and i search to transform into simple array of object like this
const experience = [
{
companyName: 'test',
postName: 'testt',
startDate: '2022-01-04',
endDate: '',
description: ''
},
{
companyName: 'stet',
postName: 'esttest',
startDate: '',
endDate: '',
description: 'stetset'
}
]
>Solution :
Write a function to extract data, I have tried it:
const obj = {
'experience[0].companyName': 'test',
'experience[0].postName': 'testt',
'experience[0].startDate': '2022-01-04',
'experience[0].endDate': '',
'experience[0].description': '',
'experience[1].companyName': 'stet',
'experience[1].postName': 'esttest',
'experience[1].startDate': '',
'experience[1].endDate': '',
'experience[1].description': 'stetset'
}
let finalArr = []
for (key in obj) {
// code block to be executed
let finalValue = obj[key];
let attributeArr = key.split(".");
let numberPattern = /\d+/g;
//get the index of the data
let index = attributeArr[0].match( numberPattern )
index = Number(index)
let thisObj = finalArr[index]
if(!thisObj){
thisObj = finalArr[index] = {}
}
thisObj[attributeArr[1]] = finalValue
}
console.log(finalArr)