-1

From the below json, how do I retrieve object based on given applicationName

{
    "apps": [
        {
            "applicationName": "myTestApp",
            "keys": [
                {
                    "key": "app-key",
                    "value": "ZDM0"
                },
                {
                    "key": "env-key",
                    "value": "YTE1Mm"
                }
            ]
        },
        {
            "applicationName": "hello",
            "keys": [
                {
                    "key": "app-key",
                    "value": "ZjIwZT"
                },
                {
                    "key": "env-key",
                    "value": "MDExMTc5N2"
                }
            ]
        }
    ]
}

So if my input is myTestApp, I want to get myTestApp object

{
    "applicationName": "myTestApp",
    "keys": [
        {
            "key": "app-key",
            "value": "ZDM0"
        },
        {
            "key": "env-key",
            "value": "YTE1Mm"
        }
    ]
}
Magicprog.fr
  • 4,072
  • 4
  • 26
  • 35
iLaYa ツ
  • 3,941
  • 3
  • 32
  • 48
  • Pet peeve: This is a JS object, or just an object. `"{\"a\": 2}"` is an example of JSON string. There is only one JSON object in JavaScript, and it has properties `parse` and `stringify`. – Amadan Jul 10 '15 at 10:04

3 Answers3

5

This should do the trick:
(assuming your data is the variable the data is stored in)

var result = data.apps.filter(function(app){
    return app.applicationName === "myTestApp";
});

if(result.length){         // If there are any results, then
    console.log(result[0]) // `result[0]` is the app with the right name.
}
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • Thanks. +1 for using filter. For a knowledge, Which one will be fast by using filter or loop? – iLaYa ツ Jul 10 '15 at 10:21
  • A broken loop will probably be a little faster (Not enough to notice a difference, both are damn fast already). However, the `filter` will return _all_ results, the `for` loop only the first result. – Cerbrus Jul 10 '15 at 10:23
2

var jsonData; // put your json data here

var appsArr = jsonData.apps;

for (var i in appsArr) {
   if(appsArr[i].applicationName == "myTestApp") {
      var requiredObj = appsArr[i];
      break;
   }
}

requiredObj is the object you want.

Suman Barick
  • 3,311
  • 2
  • 19
  • 31
0

You should iterate through your JSON array and check the values of applicationName. Check this fiddle

http://jsfiddle.net/bcudcyf6/1/

var object = yourJSONdata;
for(var i in object.apps){
if("hello" == object.apps[i].applicationName)
    alert(i);
}

If your JSON is too big you can also use an external javascript library like Defiant (http://www.defiantjs.com/) which make searching easy and fast

JcDenton86
  • 933
  • 1
  • 12
  • 32