0

I have the following json string as a variable jsonString.

[  
   {  
      "id":1,
      "created_at":"2016-12-01 12:28:52",
      "updated_at":"2016-12-01 13:02:49",
      "title":"Company 1",
      "text":null,
      "url":"http:\/\/somesite.co.uk\/",
      "is_active":1,
      "api":"309809458909",
      "list":"343242344344"
   },
   {  
      "id":2,
      "created_at":"2016-12-01 12:59:51",
      "updated_at":"2016-12-01 12:59:51",
      "title":"Company 2",
      "text":null,
      "url":"http:\/\/secondsite.co.uk/",
      "is_active":1,
      "api":"309809809809",
      "list":"890890809809"
   }
]

I would like to match by url and then return the data in that ID.

So searching http://secondsite.co.uk would return all the data in that particular object.

I have tried the following but not sure if this is the way to go. (based on https://gist.github.com/iwek/3924925#file-find-in-json-js)

//return an array of keys that match on a certain value
function getKeys(obj, val) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            objects = objects.concat(getKeys(obj[i], val));
        } else if (obj[i] == val) {
            objects.push(i);
        }
    }
    return objects;
}


var json = jsonString;

var js = JSON.parse(json);

//example of grabbing keys by searching via values in JSON
console.log('06' + getKeys(js,'http://secondsite.co.uk/'));

But it doesn't return the results. Is there a better to do this?

ServerSideSkittles
  • 2,713
  • 10
  • 34
  • 60

0 Answers0