我有一个这样的对象:
{
"responses": {
"firstKey": {
"items": {
"name": "test name one"
}
},
"anotherKey": {
"items": {
"name": "test name two"
}
},
"oneMoreKey": {
"items": {
"name": "John"
}
}
}
}
我需要找到所有“名称”键并仅当它以“测试名称”开头时才替换其值,然后返回新的 JSON 对象:
{
"responses": {
"firstKey": {
"items": {
"name": "N/A"
}
},
"anotherKey": {
"items": {
"name": "N/A"
}
},
"oneMoreKey": {
"items": {
"name": "John"
}
}
}
}
问题是键在对象中不一致,即“firstKey”、“secondKey”……我尝试了 ForEach,但它似乎太麻烦了……所以我需要 lodash 或 vanila JavaScript 来替换值。
原文由 John Glabb 发布,翻译遵循 CC BY-SA 4.0 许可协议
做这样的事情。使用正则表达式转换为字符串替换(也将键添加到正则表达式),然后再转换回来。