Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to transform oject with array inside into array?

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'
  }
]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading