0

I have some difficulties accessing the key/values inside an object even tho i have said it is an array. (.map gave me error)

With axios post i have this type in response

 type response = {
    data: [];
  };

Response from API:

"data": {
        "thisoneineed": false,
        "response": [{
            "ID": "1234",
        }],
        "message": "this is a test message",
    }

inside my components i get this from a redux state (i am saving it in the state after the response)

when i try this:

Object.entries(state).map(([key, value]) => {
  console.log(key);
})

It gives me all they keys inside the array.

What i need to do is to access the value based on a key value so i did like this: (inside a component)

 const insurance = useSelector(
    (state: AppState) => state.session.data
);

    Object.entries(insurance).map(([key, value]) => {
      console.log(key[thisoneineed]);
    })

This gives:

TS2304: Cannot find name 'thisoneineed'.

I was woundering how can i access the success key and get the value.

10
  • 1
    Why can't you do this directly insurance.thisisoneineed Commented Feb 18, 2022 at 16:02
  • TS2339: Property 'thisisoneineed' does not exist on type '[]'. Commented Feb 18, 2022 at 16:04
  • But insurance is an array or a JSON? Commented Feb 18, 2022 at 16:06
  • console.log(typeof(insurance)); this gives me "object" Commented Feb 18, 2022 at 16:07
  • 1
    @AliDurrani using any is not a best practice, would suggest you to figureout the exact type and use it Commented Feb 18, 2022 at 16:15

1 Answer 1

1

You have the type defined as

type response = {
    data: [];
  };

which means it's an empty array, either as hack try changing it to any until you figureout the exact type of the response and then give it a correct type

EDIT::

You can try this

 const insurance = useSelector(
    (state: AppState) => state.session.data
) as any;

console.log(insurance.thisoneineed)

PS: I wont suggest keeping any overthere but until you figure out the exact type of the response you can keep it

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

Comments

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.