Swapnil Kotwal
Swapnil Kotwal

Reputation: 5730

Check if any value in jsonPath is repeated

I have a jsonPath as below

{   "book":
        [ 
            { "category": "reference",
              "author": "Nigel Rees",
              "title": "Sayings of the Century",
              "price": 8.95
            },
            { "category": "fiction",
              "author": "Nigel Rees",
              "title": "Sword of Honour",
              "price": 12.99
            }
]}

And Want to check if any author name have got repeated? I tried

$.book[?(@.author=='Nigel Rees')].find(1)

But, it always throws an exception that found nothing, how could I check that the author='Nigel Rees' occurrences i.e author='Nigel Rees' have a two books?

Upvotes: 2

Views: 662

Answers (1)

devilfart
devilfart

Reputation: 347

Depends what you are planning on doing if the authors names exists. If you only want the objects with author of Nigel Reese you could use a filter.

    var booksByNigelReese = book.filter( function(book, index) {
        return book.author === 'Nigel Reese'
    })

.filter() takes a function that takes the book and index, chooes to accept or rejcet the book into a new array depending if the result of the function is true or false

Upvotes: 1

Related Questions