c_lejeune
c_lejeune

Reputation: 241

Dig into an object to meets a condition and returns the property that is levels above

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!

Upvotes: 1

Views: 288

Answers (2)

Eddie
Eddie

Reputation: 26854

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);

If you want multiple matches, you can use filter and map

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

let toSearch = "John";
let result = obj.objects.filter(o => o.authors.some(x => x.name === toSearch)).map(o => o.body);

console.log(result);

Upvotes: 1

Akhil Aravind
Akhil Aravind

Reputation: 6130

This may look little buggy, but you definitely get a solution

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

obj["objects"].forEach(item=>{
  if(item.authors){
		item.authors.forEach(items=>{
          if(items.name == 'Dolly') console.log(item['body'])
      })
	}
})

Upvotes: 0

Related Questions