NodeJS 在json中,找到一个包含值为'RBS'的键,然后将值'RBS'替换为另一个在节点js末尾具有相同数字的键

6ss1mwsb  于 2023-05-22  发布在  Node.js
关注(0)|答案(1)|浏览(90)

我有这个JSON数据和关键字“Label_Field_ID_1117189”具有值“RBS”,我需要替换另一个关键字“User_Answer_Field_ID_1117189”中的值“RBS”,该关键字最后具有相同的数字,即1117189。与“Label_Field_ID_1117230”相同,并替换“User_Answer_Field_ID_1117230”中的值“RBS”。需要Node js中的逻辑

[
  {
    "Author": "rps",
    "Label_Field_ID_1117189": "RBS",
    "User_Answer_Field_ID_1117189": "4532019166",
    "status": "In Bearbeitung"
  },
  {
    "Author": "sps",
    "Label_Field_ID_1117230": "RBS",
    "User_Answer_Field_ID_1117230": "4232019179"
  }
]

我需要Json看起来像下面这样

[
  {
    "Author": "rps",
    "Label_Field_ID_1117189": "RBS",
    "RBS": "4532019166",
    "status": "In Bearbeitung"
  },
  {
    "Author": "sps",
    "Label_Field_ID_1117230": "RBS",
    "RBS": "4232019179"
  }
]
nkcskrwz

nkcskrwz1#

我们可以创建一个Map函数updateAnswerFields或类似的函数来处理每个对象,将答案字段替换为相应标签字段中的正确值。
我们将使用Object.entries()来查找替换答案字段时要使用的标签和值。
答案ID将与标签ID相同,因此我们将使用标签中的ID值来组合它。
我们将使用解构赋值从返回的对象中删除答案标签,然后使用标签值进行更新。

const input = [
  {
    "Author": "rps",
    "Label_Field_ID_1117189": "RBS",
    "User_Answer_Field_ID_1117189": "4532019166",
    "status": "In Bearbeitung"
  },
  {
    "Author": "sps",
    "Label_Field_ID_1117230": "RBS",
    "User_Answer_Field_ID_1117230": "4232019179"
  }
]

function updateAnswerFields(obj) {
    const [ label, value] = Object.entries(obj).find(([key, value]) => key.startsWith('Label_Field_ID_'));
    const answerKey = 'User_Answer_Field_ID_'  + label.split('_').slice(-1)[0];
    const { [answerKey]: a, ...rest} = obj;
    rest[value] = obj[answerKey]
    return rest;
}

console.log(input.map(updateAnswerFields));
.as-console-wrapper { max-height: 100% !important; }

相关问题