Home > Enterprise >  how to transform oject with array inside into array?
how to transform oject with array inside into array?

Time:01-05

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

CodePudding user response:

In this example I make use of an imitatively invoked function expression to "evaluate" a string (like experience[0].companyName = "test") that inserts properties into an object.

The try/catch will test if an object is there (like experience[0]). If not, it troughs an error, and in the catch I push the empty object that is needed into the empty array.

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

var experience = [];

Object.keys(obj).forEach(key => {
  try {
    Function(`return ${key}`)();
  } catch (err) {
    experience.push({});
  }
  Function(`return ${key} = "${obj[key]}"`)();
});

console.log(experience);

CodePudding user response:

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)
  •  Tags:  
  • Related