1

I am getting a response from an endpoint which is this:

[[{"1":"91"}],[{"1":"1"}],[{"1":"0"}],[{"1":"0"}],[{"1":"0"}],[{"1":"0"}],[{"1":"0"}],[{"1":"0"}]]

I fetched them and I get the results but I cannot render them. This is what I have been trying:

render() {
        const {count} = this.state;
        return (
            <div>
                {count.count && count.count.map(item => (
                    item.value.map(data => (
                        data.value.map(x => (
                            <p>{x.value}</p>
                        ))
                    ))
                ))}
            </div>
        )
    }

I expect the out to be all the numbers shown in the json response. Ex. 91 1 0 0 0 etc.

7
  • please provide your sample this.state.count Commented May 28, 2019 at 12:09
  • I'm not sure what's going on. You're showing one object and handle it as it totally different. You're using 3 map while you have 2 levels in the object. Also, where value prop came from? In the object, there is not value. And you're expect the result to contains 94.. but you have no 94 in the object. Where the count come from? etc. Commented May 28, 2019 at 12:11
  • Is there any error that you are getting? Commented May 28, 2019 at 12:12
  • @DaniVijay No I am not getting any error. Commented May 28, 2019 at 12:24
  • @Ashish state = { count: {} }; Commented May 28, 2019 at 12:30

1 Answer 1

1

First of all, the structure the array you're trying to iterate is like an array of arrays, with objects within. So, start iterate first and second arrays first, then iterate the object within. Object.keys can be used for that.

You can access it like the following,

...
    <div>
      {count &&
        count.length > 0 &&
        count.map(
          item =>
            item.length > 0 &&
            item.map(
              el =>
                Object.keys(el).length > 0 &&
                Object.keys(el).map(val => <p>{el[val]}</p>)
            )
        )}
    </div>
...

Codesandbox demo here

Stackblitz demo here

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

4 Comments

Please share your state. It like, count: {count: [[{"1":"91"}],[{"1":"1"}],[{"1":"0"}],[{"1":"0"}],[{"1":"0"}],[{"1":"0"}],[{"1":"0"}],[{"1":"0"}]]}, right?
count: Array[8] 0: Array[1] 0: {…} 1: "91"
Directly iterate count then, instead of count.count. I've edited the answer. Refer codesandbox too.
stackblitz.com/edit/react-55mj54 ^ Added the array statically because the API is not available. Also added a check for count is empty or not.

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.