在javascript中将一个对象转换为多个对象[关闭]

2024-03-10

我想在 JavaScript 中将一个对象转换为多个对象。

这是我的对象:

const obj =  jQuery('.sts_create form').serializeArray();

console.log记录这个:

1
: 
{name: 'target_tag', value: 'a'}
2
: 
{name: 'animation_status', value: 'animation-1'}
3
: 
{name: 'duration', value: ''}
4
: 
{name: 'target_tag', value: 'div'}

但我需要它与此类似:

{
0 : {
target_tag:'',
animation_status:'',
duration:'',
},
1 : {
target_tag:'',
animation_status:'',
duration:'',
},
...
}

这有帮助吗?请参阅代码注释以获取有关其工作原理的一些信息。

const input_data = [
  {name: 'target_tag', value: 'a'},
  {name: 'animation_status', value: 'animation-1'},
  {name: 'duration', value: ''},
  {name: 'target_tag', value: 'div'},
  {name: 'animation_status', value: 'animation-1'},
  {name: 'duration', value: ''},
];

const collate = (input_data) => {
  const result = [{}];
  
  for(const input_info of input_data) {
    // check to see if the last item in the results array has an entry for the
    // current input name, create a new object at the end of the array if it does
    if(result[result.length - 1].hasOwnProperty(input_info.name))
      result.push({});
    
    // add entry to object at end of result array
    result[result.length - 1][input_info.name] = input_info.value;
  }
  
  // convert result array to object
  return Object.fromEntries(Object.entries(result));
};

console.log(collate(input_data));

编辑:更新collate期望一个数组而不是一个对象。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在javascript中将一个对象转换为多个对象[关闭] 的相关文章

随机推荐