{"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"} ]}
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);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments