skip to Main Content
{"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"} ]}

3

Answers


  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);
    
    Login or Signup to reply.
  2. 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); 
    
    Login or Signup to reply.
  3. To parse an object with array index to an object array with key-value pairs in JavaScript, you can use the following function:

    function parseObject(input) {
      const result = {};
      Object.keys(input).forEach((key) => {
        const index = key.indexOf("[");
        if (index > -1) {
          const root = key.substring(0, index);
          const subKey = key.substring(index + 1, key.length)
          const indexNum = parseInt(subKey, 10);
          if (!result[root]) {
            result[root] = [];
          }
          if (!result[root][indexNum]) {
            result[root][indexNum] = {};
          }
          result[root][indexNum][subKey.substring(subKey.indexOf(".") + 1)] = input[key];
        } else {
          result[key] = input[key];
        }
      });
      return result;
    }
    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 = parseObject(input);
    console.log(output);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search