0

I've been playing with json objects & using ReactJS. One of the json object represented by variable 'res'. How do I convert 'res' into 'b'. I'm also getting my json object 'res' from an api.

I've reciprocated my problem over this link: 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);
      });
    })();
  }, []);

How do I convert this:

const res = 
{
  "0": {
    "id": "1",
    "countryInfo": [
      {
        "_id": "4",
        "lat": "33"
      }
    ]
  },
  "1": {
    "id": "2",
    "countryInfo": [
      {
        "_id": "8",
        "lat": "41"
      }
    ]
  }
}

into this json object:

const b =

{
  "popup": {
    "countryInfo": [
      {
        "_id": "1",
        "lat": "33"
      },
      {
        "_id": "2",
        "lat": "41"
      }
    ]
  }
}
2
  • You'll have to just update the keys from your previous question, so instead of having menuitem you'll have countryInfo, check my answer below and let me know if it works for you. Commented Apr 20, 2020 at 2:48
  • @LuísRamalho I'm getting error: can't convert undefined to object Commented Apr 20, 2020 at 3:21

1 Answer 1

0

You basically want an identical solution to your previous question, something like:

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

Sign up to request clarification or add additional context in comments.

3 Comments

I'm getting this error: can't convert undefined to object
Basically, you cannot give the countryInfo object to MaterialTable, you'll have to destructure the properties you want from it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.