- 我有这个问题的解决方案**,但我在社区中发布这个问题,以寻找一个轻量级的或说有效的方法来做到这一点,如果可能。因此,更好的方法/建议是赞赏。
我有一个字典/键值对数据,如下所示,基本上是用于转换响应的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"
}
]
`;
2条答案
按热度按时间tgabmvqs1#
我认为您正在JSON.stringify中查找
replacer
参数:为了简单起见,我颠倒了匹配表中的键和值,但是您应该明白这个意思。
ego6inou2#
数据表述:-
输出:-