问题描述
我有这个对象:
[
{
"_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 "
}
]
我想将其重组为:
[
{"title": "Test Title","from_date": "2021-05-17","to_date": "2021-05-18","institute":"Title"},{"title": "Test TitleTest Title",{"title": "Test Title",]
我如何使用 javascript 做到这一点?或使用 javascript 的任何简单方法?
编辑: 到目前为止,我所做的是:
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.
});
}
解决方法
假设您按对象键*中的数字分组,您可以使用正则表达式将对象键分解为标签和数字,并在对象键/值对上 reduce
以创建一个使用数字作为新键的新对象。然后您可以使用 Object.values
从该对象创建一个数组。
*请注意,此输出仅生成两个对象,而不是预期输出中指示的三个对象。
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));