Akshay
Akshay

Reputation: 391

Return JSON based on not matching certain values

I am working on a JSON in javascript and want to return only values that don't contain the article word. For the below JSON

var json = [
    {
        id: 1,
        path: ["home>blog","home>article"]
    },
    {
        id: 2,
        path: ["home>blog"]
    },
    {
        id: 3,
        path: ["home>blog"]
    },
    {
        id: 4,
        path: ["home>blog","home>article"]
    },
]

And I want to get the final result as -

var final = [
    {
        id: 2,
        path: ["home>blog"]
    },
    {
        id: 3,
        path: ["home>blog"]
    }
]

How can I achieve the result?

Upvotes: 0

Views: 92

Answers (2)

Nikhil Ponduri
Nikhil Ponduri

Reputation: 531

Hope this code works

const final = json.filter(obj=>{
 for(const path of obj.path){
 if(path.includes('article') return false;
 }
return true;
});

Upvotes: 0

norbitrial
norbitrial

Reputation: 15166

Using .some() and .includes() you achieve that.

Try the following:

const json = [{ id: 1, path: ["home>blog","home>article"] }, { id: 2, path: ["home>blog"] }, { id: 3, path: ["home>blog"] }, { id: 4, path: ["home>blog","home>article"] }];

const result = json.filter(e => !e.path.some(s => s.includes('article')));

console.log(result);

I hope this helps!

Upvotes: 1

Related Questions