javascript - 将嵌套的 json 对象转换为另一个 json 对象
问题描述
我一直在玩 json 对象和使用 ReactJS。由变量“res”表示的 json 对象之一。如何将“res”转换为“b”。我还从 api 获取我的 json 对象“res”。
我已经通过此链接解决了我的问题:https ://codesandbox.io/s/epic-leaf-sznhx?file=/src/App.js
const [res, setResult] = useState();
useEffect(() => {
(async () => {
axios.get("https://corona.lmao.ninja/v2/countries").then(response => {
setResult(response.data);
});
})();
}, []);
我如何转换这个:
const res =
{
"0": {
"id": "1",
"countryInfo": [
{
"_id": "4",
"lat": "33"
}
]
},
"1": {
"id": "2",
"countryInfo": [
{
"_id": "8",
"lat": "41"
}
]
}
}
进入这个 json 对象:
const b =
{
"popup": {
"countryInfo": [
{
"_id": "1",
"lat": "33"
},
{
"_id": "2",
"lat": "41"
}
]
}
}
解决方案
您基本上想要与上一个问题相同的解决方案,例如:
const res = {
"0": {
id: "1",
countryInfo: [{
_id: "4",
lat: "33",
}, ],
},
"1": {
id: "2",
countryInfo: [{
_id: "8",
lat: "41",
}, ],
},
};
let b = Object.keys(res).reduce(
(p, c) => {
for (let item of res[c].countryInfo) {
p.popup.countryInfo.push(item);
}
return p;
}, {
popup: {
countryInfo: [],
},
}
);
console.log(b);
推荐阅读
- c++11 - 如何在 std::bind 中使用占位符
- angular - 禁止放置映射 403
- asp.net-core - .Net 核心:动态获取标头来源
- html - 一个非常非常奇怪的问题html对象标签
- json - 资源标识符格式错误的 Json 模板
- scala - NoSuchMethodError:org.json4s.FieldSerializer。
- reporting-services - 根据组和设置值的阈值
- python - 以科学计数法显示的注释
- javascript - 揭示模块模式 Javascript
- python - 无法将 .csv 转换为数据框错误:“str”对象不可调用