I've this object:
[
{
"_token": "lRM32nH7KAnt2xdDkUJBJYniNnANJVhG20BGnjHE",
"academic[2][id]": "-1",
"title[2][name]": "Test Title",
"from_date[2]": "2021-05-16",
"to_date[2]": "2021-05-17",
"institute[2]": "Titletest title test title ",
"title[3][name]": "Test TitleTest Title",
"from_date[3]": "2021-05-17",
"to_date[3]": "2021-05-18",
"institute[3]": "test title test title test title test title "
}
]
And i want to restructure it to:
[
{"title": "Test Title", "from_date": "2021-05-17", "to_date": "2021-05-18","institute":"Title"},
{"title": "Test TitleTest Title", "from_date": "2021-05-17", "to_date": "2021-05-18","institute":"Title"},
{"title": "Test Title", "from_date": "2021-05-17", "to_date": "2021-05-18","institute":"Title"},
]
How can i do this using javascript? or any simple approach using javascript?
Edit: What I've done so far is:
const data = new FormData(document.querySelector('#academic-form'));
const result = [Object.fromEntries(data.entries())][0];
const academics = [];
for(var key in result){
// console.log('key: ' + key);
console.log('title: ' + result[key]);
console.log(result[i]);
academics.push({
//push values in academics array.
});
}
Assuming you're grouping by the number in the object keys* you can use a regex to break up the object keys into into a label and number, and reduce
over the object key/value pairs to create a new object using the number as a new key. You can then use Object.values
to create an array from that object.
*Note that this output only produces two objects, not the three indicated in your expected output.
const arr = [{ "_token": "lRM32nH7KAnt2xdDkUJBJYniNnANJVhG20BGnjHE", "academic[2][id]": "-1", "title[2][name]": "Test Title", "from_date[2]": "202 1-05-16", "to_date[2]": "2021-05-17", "institute[2]": "Titletest title test title ", "title[3][name]": "Test TitleTest Title", "from_date[3]": "2021-05-17", "to_date[3]": "2021-05-18", "institute[3]": "test title test title test title test title " }]; const regex = /(title|from_date|to_date|institute)(\[\d\])/; // Iterate over the object grabbing the key and value const out = Object.entries(arr[0]).reduce((acc, [key, value]) => { // Create a match array using the regex on the key const match = key.match(regex); // If there is a match... if (match) { // Use the number in the match to create a new // key on the accumulator object if it doesn't exist, // and set it to an empty object acc[match[2]] = acc[match[2]] || {}; // Now assign a value to the property in that object // identified by the match (title, to_date etc) acc[match[2]][match[1]] = value; } // Return the accumulated object for the next iteration return acc; }, {}); console.log(Object.values(out));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.