Change keynames in an array of objects - JS

Viewed 39

I have an array of objects and I want to change the keys in 'data' array to match the label in headers array.

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)

Please advice.

Expected Result:

[{
    'First Name': 'John',
    'Last Name': 'Doe'
}, {
    'First Name': 'ABC',
    'Last Name': 'DEF'
}]
2 Answers

this way

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;}

Here's a relatively simple way of achieving this using the map method:

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);

Related