2

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 2

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

The is clearly the simpler of the two answers. I've gotta get better at using reduce… it's powerful
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.