在JavaScript/Typescript中转换/修改接收到的JSON输入响应键的优化或有效方法是什么

qv7cva1a  于 2022-12-20  发布在  Java
关注(0)|答案(2)|浏览(112)
    • 我有这个问题的解决方案**,但我在社区中发布这个问题,以寻找一个轻量级的或说有效的方法来做到这一点,如果可能。因此,更好的方法/建议是赞赏。

我有一个字典/键值对数据,如下所示,基本上是用于转换响应的Map。

KEYS  :  VALUE
 

    "score": "RelevantScore",
    "headline": "Headline",
    "subtitle1": "PublishedDate",
    "subtitle2": "Stage",
    "body": "Summary",
    "labels": "Tag"

我的目标是转换JSON输入响应,我需要用上面Map数据中Map的KEY替换旧属性(VALUE)。

    • 我有一个包含以下内容的JSON对象:****(假设已收到输入响应)**
"Data": [{
            "RowId": 1,
            "Headline": "some data",
            "PublishedDate": "2022-09-29",
            "Summary": " some data",
            "SourceURL": "https://www.google.com",
            "RelevantScore": 0,
            "Stage": null,
            "Tag": "",          
}]

我想将"RelevantScore"键更改为"score",这样它将变为**(交换后的预期输出)**

"Data": [{
            "RowId": 1,
            "headline": "some random headline",
            "subtitle1": "2022-09-29",
            "body": "some data",
            "SourceURL": "https://www.google.com",
            "score": 0,
            "subtitle2": null,
            "labels": "",
}]
  • 注意:-我们将使用上面的Map表交换密钥 *
    • 输入JSON响应属性名称将替换/交换为相应的Map键,以便可以根据旧响应精心编制新响应。**可以忽略不匹配的键

简单示例:-RelevantScore来自响应的键被其Map值Score替换,以形成新的响应对象。

    • 我拥有的现有功能:-**
function renameKey ( obj, oldKey, newKey ) {
  obj[newKey] = obj[oldKey];
  delete obj[oldKey];
}
    • 现有方法:-**
const json = `
  [
    {
      "RelevantScore":"5078c3a803ff4197dc81fbfb"
    }
  ]
`;
const arr = JSON.parse(json);
arr.forEach( obj => renameKey( obj, 'RelevantScore', 'Score' ) ); // Call to the method
const updatedJson = JSON.stringify( arr );
    • 结果**:-
const json = `
  [
    {
      "Score":"5078c3a803ff4197dc81fbfb"
    }
  ]
`;
tgabmvqs

tgabmvqs1#

我认为您正在JSON.stringify中查找replacer参数:

JSON.stringify(arr, function(key, value) {
  if (table.hasOwnProperty(key)) {
    this[table[key]] = value; // add new key
    return; // don't add old key
  }
  /* uncomment the next line if you want to add not matching keys as well */
  // return value;
});

为了简单起见,我颠倒了匹配表中的键和值,但是您应该明白这个意思。

ego6inou

ego6inou2#

transformResposne(dynamicData :any[]): any [] {

      dynamicData.forEach( obj => renameKeys( obj, new Map(Object.entries(this.controls))));
      function renameKeys( obj, columnMap : Map<string, string> ) {
        columnMap.forEach(function(oldkey, newKey) {
          if (oldkey in obj)
          {
            obj[newKey] = obj[oldkey];
            delete obj[oldkey];
          }
        })
      }
      return dynamicData;
   
  };

数据表述:-

dynamicData = [{
           "RelevantScore": 0                
     }]

   controls = {
    "score": "RelevantScore",
   }

输出:-

dynamicData = [{
               "score": 0                
         }]

相关问题