更改对象数组中的注释记号-JS



我有一个对象数组,我想更改"data"数组中的键以匹配headers数组中的标签。

const headers = [{
label: 'First Name',
field: 'firstName'
}, {
label: 'Last Name',
field: 'lastName'
}]
const data = [{
firstName: 'John',
lastName: 'Doe'
}, {
firstName: 'ABC',
lastName: 'DEF'
}]

const headers = [{
label: 'First Name',
field: 'firstName'
}, {
label: 'Last Name',
field: 'lastName'
}]
const data = [{
firstName: 'John',
lastName: 'Doe'
}, {
firstName: 'ABC',
lastName: 'DEF'
}]
const mapHeaders = headers.reduce((a, c) => {
return {
...a,
[c.field]: c.label
}
}, {})

const result = data.map(item => {
return {
...item,
[mapHeaders[item]]: item
}
})
console.log(result)

请提供建议。

Expected Result:
[{
'First Name': 'John',
'Last Name': 'Doe'
}, {
'First Name': 'ABC',
'Last Name': 'DEF'
}]

这种方式

const headers = 
[ { label: 'First Name', field: 'firstName' } 
, { label: 'Last Name',  field: 'lastName'  } 
] 
const data = 
[ { firstName: 'John', lastName: 'Doe' } 
, { firstName: 'ABC',  lastName: 'DEF' } 
]

const res = data.map( o => headers.reduce((a,c)=>
{
a[c.label] = o[c.field]
return a
},{}))

console.log( res)
.as-console-wrapper {max-height: 100%!important;top:0;}

这里有一个使用map方法实现这一点的相对简单的方法:

const headers = [{
label: 'First Name',
field: 'firstName'
}, {
label: 'Last Name',
field: 'lastName'
}]
const data = [{
firstName: 'John',
lastName: 'Doe'
}, {
firstName: 'ABC',
lastName: 'DEF'
}]
const newData = data.map(e => Object.fromEntries(Object.entries(e).map(f => f.map((g,i) => i ? g : headers.find(h => h.field === g) ? headers.find(h => h.field === g).label : g))));
console.log(newData);

最新更新