1

I have an API returning data in a deeply nested objects within an object within an object format. I am attempting to grab data from some of these deeply nested objects and iterate through them and display them in a React project.

This have been a massive headache and I can't find anything reasonably simple that works.

Lets say I have JSON data that looks like this:

Object {
   Object2 {
     Object3 {
       propertyIWantToAccess1: 'some data',
       propertyIWantToAccess2: 'some more data',
       propertyIWantToAccess3: 10,
       propertyIWantToAccess4: true
     }
   }
}

How can I, in the render or return function of a component, iterate through these nested objects and grab the properties I want? I think some variation of nested Object.keys.map might be the way to go but I am unsure about how to do this.

Does this need to involve es6 destructuring (a concept that I am not yet comfortable with) or a library like lo-dash?

Edit for clarification: The data is not an array containing objects. It is an object containing many nested objects

I have the data in the API stored in this.state.myPosts

I can console.log the nested object like so:

    const data = this.state.myPosts;

    const posts = data.content;

    console.log(posts);

But when I try to map through the nested object's property using that posts variable I get an error. This doesn't work:

render() {
    // Logs data
    console.log(this.state.myPosts);

    const data = this.state.myPosts;

    // Stores nested object I want to access in posts variable
    const posts = data.content;

    // Successfully logs nested object I want to access
    console.log(posts);

    // Error, this will not allow me to pass posts variable to Object.keys
    const display = Object.keys(posts).map(key =>
      <option value={key}>{posts[key]}</option>
    )


    return(
      <div>
        {display}
      </div>
    );
  }

I get a TypeError: can't convert undefined to object error. It won't allow me to pass the posts variable to Object.keys. Why?

4
  • Is the returned data structure from the network request an array of these deeply nested objects? Or is it one large object, that can contain several objects at each step down in the hierarchy? Commented Jun 20, 2018 at 19:12
  • 1
    I think Object.keys is a good way to iterate over a javascript object properties. Can you show us what you've done so far? Commented Jun 20, 2018 at 19:15
  • The outermost data structure is an Object. So it's one big Object with a bunch of nested Objects. Commented Jun 20, 2018 at 19:15
  • I updated the post to include the code I am working with. Any ideas? Commented Jun 20, 2018 at 20:47

4 Answers 4

1

If you simply need to search into a Json string or data, you could use a query language for that:

https://www.npmjs.com/package/json-query

(an equivalent of XQuery for JSON)

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

2 Comments

The thing is I'm not trying to just search for one or two properties from that object. The API contains blog posts from a social media site and hardcoding this wouldn't be doable. I'm just baffled there isn't a common pattern for dealing with deeply nested objects in React.
Took a closer look at this and it worked well for me. Thanks.
1

What you need is a recursive search, which are complicated and intimidating at first but do become much easier to write with practice. It would be hard for React maintainers to provide a tool that's exactly what you want but there are plenty of utilities in the JS ecosystem to help you.

An example using lodash that searches a nested object for the key 'pizza' and returns an array of the values:

let { reduce } = require('lodash')
const o = { one: { pizza: 1, spaghetti: 2 }, pizza:3 }

const f = (o) => reduce(o, (acc, val, key) => {
    if(typeof val == 'object') acc = acc.concat(f(val))
    else if (key == 'pizza') acc = acc.concat(val)
    return acc
}, [])
f(o)
>[1,3]

But it looks like you will want to use a regex search to find your keys, e.g. with String.prototype.match

Comments

1

I can console.log the nested object like so:

const data = this.state.myPosts;

const posts = data.content;

console.log(posts);

But when I try to map through the nested object's property using that posts variable I get an error.

The real reason is TIME

In react when component loads data render is called (at least) twice - once on mounting (initial state, no data yet) and second time forced by setState (with loaded data). It's well known problem and simple to resolve - just test for object property at appropiate level:

render() {
    // Logs data
    console.log(this.state.myPosts);

    const data = this.state.myPosts;

    // Stores nested object I want to access in posts variable
    const posts = data.content;

    // Successfully logs nested object I want to access
    console.log(posts);

    if(!posts) return <Loading/>

    //
    // there you can safely use posts for looping
    //

1 Comment

this was true for me because my state was being set by an async fetch. errors were being thrown before I had the data return from the fetch.
1

May be late for that, but the flat library met my needs. It contains the methods flatten and unflatten, in case you want plain objects or not.

https://www.npmjs.com/package/flat

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.