-2
{"SubmitBy":"SK", "Students[0].name":"Jhon", "Students[0].age":"15", "Students[1].name":"Sam", "Students[1].age":"16", "Students[2].name":"Tom", "Students[2].age":15} 

Result expecting like this

{SubmitBy:"SK", Students:[{name:"Jhon", age:"15"},{name:"Sam", age:"16"},{name:"Tom", age:"15"} ]}
  • duplicate: [Javascript: Convert dot-delimited strings to nested object value](https://stackoverflow.com/questions/28058519/javascript-convert-dot-delimited-strings-to-nested-object-value) – pilchard Apr 26 '23 at 10:05
  • or [tree from array of dot-separated strings](https://stackoverflow.com/questions/62490323/tree-from-array-of-dot-separated-strings) – pilchard Apr 26 '23 at 10:05

2 Answers2

0

You can use library like dot-prop to achieve this, code below:

import { setProperty } from 'dot-prop';

const input = {
  SubmitBy: 'SK',
  'Students[0].name': 'Jhon',
  'Students[0].age': '15',
  'Students[1].name': 'Sam',
  'Students[1].age': '16',
  'Students[2].name': 'Tom',
  'Students[2].age': 15
};
const output = {};

for (const [key, value] of Object.entries(input)) {
  setProperty(output, key, value);
}
console.log(output);
AngYC
  • 3,051
  • 6
  • 20
0
const originalData = {"SubmitBy":"SK", "Students[0].name":"Jhon", "Students[0].age":"15", "Students[1].name":"Sam", "Students[1].age":"16", "Students[2].name":"Tom", "Students[2].age":15};

const transformedData = { SubmitBy: originalData.SubmitBy, Students: [] };

for (let i = 0; i < 3; i++) {
  const student = {
    name: originalData[`Students[${i}].name`],
    age: originalData[`Students[${i}].age`].toString(),
  };
  transformedData.Students.push(student);
}

console.log(transformedData); 
Rohit Chugh
  • 59
  • 1
  • 7
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 27 '23 at 00:47