英文:
In a json, find a key which contains value as 'RBS' and then replace the value 'RBS' in another key which has the same digits at the end in node js
问题
以下是翻译后的JSON数据:
[
{
"Author": "rps",
"Label_Field_ID_1117189": "RBS",
"RBS": "4532019166",
"status": "In Bearbeitung"
},
{
"Author": "sps",
"Label_Field_ID_1117230": "RBS",
"RBS": "4232019179"
}
]
这是您所需的JSON格式。
英文:
I have this JSON data and key "Label_Field_ID_1117189" has values "RBS" and I need to replace the value "RBS" in another key "User_Answer_Field_ID_1117189" which has the same digit at last i.e 1117189. and also same with the "Label_Field_ID_1117230" and replace the value "RBS" in "User_Answer_Field_ID_1117230".
Need the logic in 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"
}
]
I need Json to look like this below
[
{
"Author": "rps",
"Label_Field_ID_1117189": "RBS",
"RBS": "4532019166",
"status": "In Bearbeitung"
},
{
"Author": "sps",
"Label_Field_ID_1117230": "RBS",
"RBS": "4232019179"
}
]
答案1
得分: 0
我们可以创建一个映射函数 updateAnswerFields
或类似的函数来处理每个对象,将答案字段替换为相应标签字段的正确值。
我们将使用 Object.entries()
来查找标签和要在替换答案字段时使用的值。
答案ID将与标签ID相同,因此我们将使用来自标签的ID值来构成答案ID。
我们将使用解构赋值来从返回的对象中删除答案标签,然后更新为标签值。
英文:
We can create a mapping function updateAnswerFields
or similar to process each object, replacing the answer field with the correct value from the corresponding label field.
We'd use Object.entries() to find the label and value to use when replacing the answer field.
The answer ID will be the same as the label ID, so we'll compose this using the ID value from the label.
We'll use the de-structuring assignment to remove the answer label from the returned object, then update with the label value.
<!-- begin snippet: js hide: false console: true babel: null -->
<!-- language: lang-js -->
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));
<!-- language: lang-css -->
.as-console-wrapper { max-height: 100% !important; }
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论