ReactJs Dig into an object to meets a condition and returns the property that is levels above reactjs into application,reactjs scroll into view,integrating react into

Considering the following object

{
"objects": [
    {
        "body": "body 1", 
        "title": "Jolene", 
        "authors": [{
            "name": "Dolly"
        },
        {
            "name": "John"
        }]
    },
    {
        "body": "body 2", 
        "title": "Jolene", 
        "authors": [{
            "name": "Dolly Parton"
        }]
    }
]
}

My goal to verify each object authors property and if one of the authors name meets the criteria I want it to return the body of such object.

For instance, I want to render the body content of the object that has at least one authors name equal to "John". In this case "body 1" should be returned.

I have tried with mapping and filtering but I can't figure out how to dig into each object to verify that condition and then return a property that lives in a higher level.

Please help! Thanks a lot!

Answer:1

You can use find to search for the first match. Use some to check whether at least one name matches.

let obj={"objects":[{"body":"body 1","title":"Jolene","authors":[{"name":"Dolly"},{"name":"John"}]},{"body":"body 2","title":"Jolene","authors":[{"name":"Dolly Parton"}]}]}

let toSearch = "John";
let result = (obj.objects.find(o => o.authors.some(x => x.name === toSearch)) || {body: ""}).body;

console.log(result);
Answer:2



  1. reactjs into application
  2. reactjs scroll into view
  3. integrating react into a php application
  4. reactjs push into state
  5. reactjs insert variable into string
  6. image into reactjs
  7. reactjs add object into array
  8. import js into react

My app is structured as follows: <App> <SelectItems/> <Tabs> <Tab> <Window1> </Tab> <Tab> <Window2> </Tab> </Tabs&...

My app is structured as follows: <App> <SelectItems/> <Tabs> <Tab> <Window1> </Tab> <Tab> <Window2> </Tab> </Tabs&...

Iam trying to convert all selected item id's from a redux store into the item names and save it into state. My problem is that the spread operator inside the setState function is equal to zero. Do I ...

Iam trying to convert all selected item id's from a redux store into the item names and save it into state. My problem is that the spread operator inside the setState function is equal to zero. Do I ...