我正在解析以下内容:
json.listMap.forEach((listItem: { State: string; Country: string})```
Response.data looks like this:
```{
success: true,
listMap:[
{
State : 'Northrine Westfalia',
Country: 'Germany'
},
{
{
State : 'Bavaria',
Country: 'Germany'
}
}
]
}
在使用Java Script从API解析后,如何将当前为'Deutschland‘的国家的值转换为’Deutschland‘?
->让我在这里更加开放。我真的不知道我能用来做这件事的方法。也许有人可以给我指点文档,当然我不期望任何人只是把代码交给我。
发布于 2021-10-01 09:33:08
下面是传递数据、from和to参数的一般方法。然后,它使用map
返回一个新的对象数组,并在必要时更改国家。
注意:检查您的数据是否有错误,因为在您的示例中有一些备用的括号。
const data = {
success: true,
listMap: [{
State: 'Northrine Westfalia',
Country: 'Germany'
},
{
State: 'Bavaria',
Country: 'Germany'
}
]
}
function swap(data, prop, from, to) {
return data.listMap.map(obj => {
// Copy the object otherwise we'll return
// an array of objects that point
// to the old references
const newObj = {...obj};
if (newObj[prop] === from) newObj[prop] = to;
return newObj;
});
}
console.log(swap(data, 'Country', 'Germany', 'Deutchland'));
console.log(swap(data, 'State', 'Bavaria', 'New Bavaria'));
发布于 2021-10-01 09:29:37
将JSON解析成JavaScript数组后使用Array.map:
const list = response.listMap.map(entry => {
return {
State : entry.State,
Country: entry.Country.replaceAll('Germany', 'Deutschland')
}
})
当然,如果您需要JSON结构,只需使用以下代码将最终数组转换为JSON字符串:
const newJSONList = JSON.stringify(list);
发布于 2021-10-01 09:30:11
试试这个:
listMap = listMap.map(listMapItem => {
if ('Germany'===listMapItem.Country) {
listMapItem.Country = 'Deutschland';
return listMapItem;
} else {
return listMapItem;
}
});
https://stackoverflow.com/questions/69409835
复制相似问题