简体   繁体   English

如何 map JSON 键动态

[英]How to map a JSON key dynamically

So I have an initial JSON object coming from an API call.所以我有一个来自 API 呼叫的初始 JSON object 。 I need to map this data to a second JSON object which will then be consumed by the application.我需要将此数据 map 到第二个 JSON object 然后由应用程序使用。 The initial object from the API calls looks something like this...来自 API 调用的初始 object 看起来像这样......

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.如果 initialData 中要更改的键的名称(例如,有人进入数据库并决定 Forename 应该是 FirstName),那么我提取的数据不再正确映射并且我的应用程序中断。 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.使用 JavaScript 方法 Object.keys() 获取 object 的密钥。
  2. Map the values of the object to their new value names Map 将 object 的值改为它们的新值名称

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.因此,我建议您不要尝试更改数据库条目的名称,除非绝对必要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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