Danny Dyer Danny Dyer - 1 month ago 8
React JSX Question

Accessing object within object by value

I am learning React-Redux and I have an issue navigating through the objects in my JSON file. I have the following file JSON, the file is designed to render out a side navigation:

export default function(){
return [
{
catId:"parMenu1",
parentCat:"Genres",
subcat:[
{
genre:"8Bit",
genreId:"1"
},
{
genre:"Acid House",
genreId:"2"
}
]
},
{
catId:"parMenu2",
parentCat:"sounds",
subcat:[
{
genre:"blah",
genreId:"3"
},
{
genre:"blah House",
genreId:"4"
}
]
]
}


I have the JSON file mapped to state props for a component. The component looks like so:

class BrowseByCont extends Component {
render () {
return (
<div className="browseByContInner">
{
console.log(this.props.reducerSidenav[0].catId)
}
</div>
)
}
}


function mapStateToProps(state) {
return {
reducerSidenav:state.reducerSidenav
};
}


I am trying to reach the subcats object within the parent object. The JSON object is linked to a variable called "reducerSidenav". So far I have managed to get this far into my JSON file:
this.props.reducerSidenav[0].catId
. this spits out the value
parMenu1
which is the "parent" object I want to target. Where I am stuck though is I am trying to achieve two things:

firstly - I would like to access the first "parent" object by without having to refer to the first item in the array:
reducerSidenav[0]
but rather by find the
catId
with a value of
parMenu1
. This is because this list will be dynamic in future and referring to the first array object is not reliable.

secondy - I would then like to access the
subcat
object and get to the value thats associated to the key
genre
ie to return the value "8Bit"

QoP QoP
Answer

You can use .find() to achieve both things.

class BrowseByCont extends React.Component {  
    render () {
        let first = this.props.reducerSidenav.find(item => item.catId === "parMenu1");
        let second = first.subcat.find(subcat => subcat.genre === "8Bit")
        return (
            <div className="browseByContInner">
                <div>{first.catId}</div>
                <div>{second.genre}</div>
            </div>
        )
    }
}

Edit

In order to print all the subcats, you have to use .map()

class BrowseByCont extends React.Component {  
    render () {
        let first = this.props.reducerSidenav.find(item => item.catId === "parMenu1");
        return (
            <div className="browseByContInner">
                {first.subcat.map(genreItem => 
                    <div key={genreItem.genreId}>{genreItem.genre}</div>)
                }
            </div>
        )
    }
}

jsfiddle