我有一个这样对象数组
let data =
[
{
text: 'label'
},
{
text: 'username'
},
{
text: 'category'
},
{
text: 'book'
},
{
text: 'john'
},
{
text: 'education'
},
{
text: 'car'
},
{
text: 'doe'
},
{
text: 'automotive'
},
{
text: 'shoes'
},
{
text: 'cena'
},
{
text: 'fashion'
},
]
以及我期望对象数组
let result =
[
{
label: 'book',
username: 'john',
category: 'education'
},
{
label: 'car',
username: 'doe',
category: 'automotive'
},
{
label: 'shoes',
username: 'cena',
category: 'fashion'
},
]
3条答案
按热度按时间fd3cxomn1#
一个简单的
for
循环可能是最清楚的。这里将每个对象存储在一个temp
变量中,以避免每次迭代都要访问结果数组的末尾,并将size
抽象为一个变量。x6h2sr282#
使用
switch-case
和modulo%
运算符检查当前密钥如何:ajsxfq5m3#
根据您的数据,前3条记录是属性名称,其他记录是数据,因此我们可以使用
Array.slice()
来获取属性名称然后,我们可以使用
Array.reduce()
转换左侧数据