1

Exist any approach to make query in json using Javascript?

Particularly I have a json in a variable json into my code javascript, this json is a array of data, each data have 3 attributes 'name', 'city' and 'age', and I want to retrieve all the data who name is 'pepe'.

Also I want to retrieve all the data with diferent name. For example if I have 3 data in the json, two of them has the same name, I want to retrieve only two object, I will be agreeable with the count of the row with different name.

How can I do this?

2 Answers2

2

You will have to parse your json string first:

var array = JSON.parse(yourString);

Then you can filter your array:

var matches = array.filter(function(x) { return x.name == 'pepe' });

This will give you a new array with only the matching elements. If you need the result as json again, you can convert it back like this:

var resultString = JSON.stringify(matches);
lex82
  • 11,173
  • 2
  • 44
  • 69
0

In addition you can use Lodash or Underscore library as the following:

    var arr = [
        {
            name: 'pepe',
            city: 'first city',
            age : 19
        },
        {
            name: 'second name',
            city: 'second city',
            age : 19
        },
        {
            name: 'third name',
            city: 'third city',
            age : 19
        }
    ]
    _.find(arr, {name:'pepe'})

Underscore: is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects.

lodash: A JavaScript utility library delivering consistency, modularity, performance, & extras.

Eymen Elkum
  • 3,013
  • 1
  • 20
  • 34