-1

I'm really new in react and i am trying axios to get some data and then with a post request update them. This is my object

{
"id": "text",
"users": {
    "George": {
        "age": "6"
    }
}}

In my code i am trying to get "George" age like this:

const [subparameters, setSubParameters] = React.useState(null);
const params = [];
      for (const [key, value] of Object.entries(r.data.users.George)){
        const _parm = {parKey: key, parValue: value };
        console.log(_parm);
        params.push(_parm);
        setSubParameters(params)
      }

But in my POST request "George" changes and r.data.parameters.George doesn't work anymore because instead of this name is another one. any ideas of solving this somehow?

5
  • You can use r.data.users[Object.keys(r.data.users)[0]]. Commented Oct 12, 2021 at 10:24
  • Do upvote, if it helps :) Commented Oct 12, 2021 at 14:26
  • @FarrukhRashid this r.data.users[Object.keys(r.data.users)[0]] only returns George but if my JSON is like this after post request: "users": { "George": { "age": "6" }, "Maria": { "age": "7" }, "Amy": { "age": "8" } } how do i get each different name object key value? Because i want to compare it with another variable. Commented Oct 13, 2021 at 11:33
  • The Object.keys(r.data.users) returns an array of all the names, i.e ["george", "maria"]. You can map through it and compare. Commented Oct 13, 2021 at 13:07
  • @FarrukhRashid you are right! thank you!! Commented Oct 13, 2021 at 13:16

1 Answer 1

0

Instead of mapping over r.data.users.George, map over r.data.users:

for (const [key, value] of Object.entries(r.data.users)){
        const _parm = {parKey: key, parValue: value }; // key = Geroge, value = {age: 6}
        console.log(_parm);
        params.push(_parm);
        setSubParameters(params)
      }
Sign up to request clarification or add additional context in comments.

2 Comments

actually the value of the mapping you suggeted is value ={"age": "6"}
Yep, you are correct. Do you want to get key=age , value=6 or key=George, value=6?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.