-2

Convert this object Students object to one Students array

{"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"} ]}
2

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

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); 

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.