简体   繁体   中英

How to map a JSON key dynamically

So I have an initial JSON object coming from an API call. I need to map this data to a second JSON object which will then be consumed by the application. The initial object from the API calls looks something like this...

const initialData =  {
        "PersonId": 1234,
        "Surname": "Blogs",
        "Forename": "Joe"
        }

and it needs to look like this to be consumed by the front end...

{
    "IdNumber": 1234,
    "Last_name": "Blogs",
    "First_name": "Joe"
}

Initially I wrote this...

const mappedData = (initialData) => {
   return {
        "IdNumber": initialData.PersonId,
        "Last_name": initialData.Surname,
        "First_name": initialData.Forename
   }
} 

The problem with this is the lack of flexibility. If the name of a key in initialData where to change (someone goes into the database and decides Forename should be FirstName for example) then the data I pull in is no longer mapped correctly and my app breaks. Can someone explain how/if this can be done dynamically?

Thanks!

First and foremost, I would advise you and the people in your team not to change the names of the database entries, and cannot find a clear reason anyone would do so. However, if you do want to change the names, the best practice would be to change the name of the entries both in the front-end and in the backend.

If you still want to do this dynamically, a good way would be to:

  1. Use the JavaScript method Object.keys() to get the keys of the object.
  2. Map the values of the object to their new value names

This would be an example:


function changeObjectNames(initialData) {
  const keys = Object.keys(initialData);

  return {
        "IdNumber": initialData[keys[0]],
        "Last_name": initialData[keys[1]],
        "First_name": initialData[keys[2]]
  }
}

There is a problem with my proposed solution: that the data might appear in the wrong order. For the time being, this is the best answer I can provide. Therefore, I would advise you not to try to change the names of the database entries unless when it's absolutely necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM