【问题标题】:Convert nested json object into another json object [duplicate]将嵌套的json对象转换为另一个json对象[重复]
【发布时间】:2020-04-20 02:41:53
【问题描述】:

我一直在玩 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"
      }
    ]
  }
}

【问题讨论】:

  • 您只需要更新上一个问题中的密钥,因此您将拥有countryInfo,而不是countryInfo,请查看下面的答案并让我知道它是否适合您.
  • @LuísRamalho 我收到错误:无法将未定义转换为对象

标签: javascript json reactjs nested


【解决方案1】:

您基本上想要与上一个问题相同的解决方案,例如:

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);

【讨论】:

猜你喜欢
  • 2018-11-23
  • 1970-01-01
  • 2015-03-13
  • 2019-07-04
  • 1970-01-01
  • 1970-01-01
  • 2021-10-30
  • 2017-10-02
  • 1970-01-01
相关资源
最近更新 更多