微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 javascript 重构 json 对象

如何解决使用 javascript 重构 json 对象

我有这个对象:

[
    {
        "_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));

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。