TheBlackBenzKid TheBlackBenzKid - 1 month ago 7
JSON Question

How can search JSON for a value key and return the nested data?

The below block is my JSON. The -KTYLrHDHt234rFDNHrm type hashes are generated by the supplied API of the client. I think they're using Firebase.

I am passing a query in the URL which contains the pageId for each of those nested objects.

Example https://cms.app.io/edit/Nike3243

But since the hash is auto generated how can I search through all the JSON and check if the pageId matches my Angular route and then only return the values of the same child.

{
"-KTYLrHDHtdq23423NHrm": {
"pageCreation": "10/8/2016, 14:14:22 PM",
"pageGallery": {
"slider_1_img": "http://",
"slider_2_img": "http://",
},
"pageId": "Nike13243",
"pageName": "Nike Campaign 1",
"store": "11"
},
"-KTYLrHDHtdqirFDNHrm": {
"pageCreation": "10/8/2016, 12:14:22 AM",
"pageGallery": {
"slider_1_img": "http://",
"slider_2_img": "http://",
},
"pageId": "Nike323243",
"pageName": "Nike Campaign 2",
"store": "12"
},
"-KTYLrHDHt234rFDNHrm": {
"pageCreation": "10/8/2016, 13:14:22 PM",
"pageGallery": {
"slider_1_img": "http://",
"slider_2_img": "http://",
},
"pageId": "Nike3243",
"pageName": "Nike Campaign 3",
"store": "13"
}
}


So I want to return only the data of Nike3243 but I want to return the store, the slider and the pageName. How can I do this since the KTYLrHDHt234rFDNHrm hash is something I will never know

cmsApp.controller('pages-edit', function ($scope, $http, $routeParams) {

var pageIdU = $routeParams.id;

$http.get(firebase_url+'cms/home.json'+randstatus).success(function(data) {
$scope.pages = data;
// this would be pageId = Nike3243
console.log(data.pageIdURI.pageName[pageId]);
});
});


Thanks

Answer

Assuming your object is called 'objTest', you could do something like this:

    var strPageId = 'The page id to find', objFound;

    for( var strKey in objTest ) {
       var objTemp = objTest[strKey];
       if ( objTemp['pageId'] == strPageId ) {
         objFound = objTemp;
         break;
       }
    }
    if ( typeof objFound == "object" ) {
    //Do something...object has been found!
    }

I actually did this:

$.each(data, function (bb) {
          var crossReference = data[bb].transId;
          if (crossReference==pageIdUri) {
            $scope.transNameEn = data[bb].transNameEn;
            $scope.transNameArabic = data[bb].transNameArabic;
            $scope.transCreation = data[bb].transCreation;
            $scope.transModified = data[bb].transModified;
            $scope.notes = data[bb].notes;
          }
        });
Comments