0

I need a way of searching a JSON object based on an ID in the object. I want to use the data in the object for a JS template.

In the moments object there are multiple (data-stamped named) arrays containing multiple objects.

I am happy to use jQuery.

Here is my JavaScript object example:

{
    "moments": {
        "20150608": [
            {
                "id": 2,
                "created": "2015-06-10T09:28:59+00:00",
                "updated": "2015-06-10T09:28:59+00:00",
                "title": "...",
                "emotion": "...",
                "context": "...",
                "description": "...",
                "published": "2015-06-09T22:34:27+00:00",
                "live": true,
                "deleted": false,
                "metric": "bio",
                "image_id": "5578035a6996d.jpg"
            },
            {
                "id": 3,
                "created": "2015-06-10T09:28:59+00:00",
                "updated": "2015-06-10T09:28:59+00:00",
                "title": "...",
                "emotion": "...",
                "context": "...",
                "description": "...",
                "published": "2015-06-09T22:34:27+00:00",
                "live": true,
                "deleted": false,
                "metric": "soc",
                "image_id": "5578035a6996d.jpg"
            }
        ],
        "20150609": [
            {
                "id": 1,
                "created": "2015-06-10T09:28:59+00:00",
                "updated": "2015-06-10T09:28:59+00:00",
                "title": "...",
                "emotion": "...",
                "context": "...",
                "description": "...",
                "published": "2015-06-09T22:34:27+00:00",
                "live": true,
                "deleted": false,
                "metric": "bio",
                "image_id": "5578035a6996d.jpg"
            },
            {
                "id": 4,
                "created": "2015-06-10T09:28:59+00:00",
                "updated": "2015-06-10T09:28:59+00:00",
                "title": "...",
                "emotion": "...",
                "context": "...",
                "description": "...",
                "published": "2015-06-09T22:34:27+00:00",
                "live": true,
                "deleted": false,
                "metric": "atm",
                "image_id": "5578035a6996d.jpg"
            }
        ]
    }
}
zizther
  • 814
  • 1
  • 10
  • 26
  • There is no "hash" in javascript. JSON is just text. What do you want the output to look like? – RobG Jun 12 '15 at 09:03
  • Thanks @RobG my mistake. I don't mind how it looks. I just need to find a way I can easily search the JSON based on the ID of an object in all arrays. I then want to use all that objects data for a JS template – zizther Jun 12 '15 at 09:05
  • A JavaScript `Object` is already a hash table. What are you actually trying to do? – Phylogenesis Jun 12 '15 at 09:05
  • since your example is already in text form as json, just use a regular string hashing function ( see [this post](http://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery) ). maybe also add some context about your purpose – amdixon Jun 12 '15 at 09:06
  • @Phylogenesis I have updated the question. Basically I need to search the JSON based on the ID of an object so that I can use the object data in a JS template – zizther Jun 12 '15 at 09:14
  • @zizther— *moments* is an object, it's properties aren't in any order. The property values are arrays, ids are unique within each array but not within the *moments* object. You can create unique keys based on each moment and id (say `'20150608:1'`, is that what you want? Or do you want an object with ids as keys and an array of the *moments* properties that contain those ids, e.g. `{1:['20150608', '20150609']}`, or something else? – RobG Jun 12 '15 at 09:39

3 Answers3

0

Here is .grep function, by using this we can make query on json array. Refer below example for this:

var arr = [ 1, 9, 3, 8, 6, 1, 5, 9, 4, 7, 3, 8, 6, 9, 1 ]; // defined array, here you can set ur json

Below is javascript function which filters array data

$(document).ready(function(){  
   var result = $.grep(arr, function(n,i){     
     return n == 1; //here add the condition which result is required
   });
  alert(result); // here you can make operation which you want to perform on      result data
});

Refer below link for more details jQuery.grep()

Rohit Sonaje
  • 522
  • 4
  • 14
0

Based on your comments, a simple search can be performed as follows:

function search(data, id) {
    for (var moment in data.moments) {
        for (var i = 0; i < data.moments[moment].length; i++) {
            if (data.moments[moment][i].id === id) {
                return data.moments[moment][i];
            }
        }
    }

    return null;
}

var result = search(jsonData, 2);
Phylogenesis
  • 7,775
  • 19
  • 27
0

It seems that moments is an object whose properties are dates. Each date has an array of moment objects, and ID is unique to each moment. You can create an object whose keys are the IDs and values are references to the moment objects containing the ID:

function generateIndex(moments) {
  var keys = {};
  Object.keys(moments).forEach(function(date) {
    var arr = moments[date];
    arr.forEach(function(moment) {
      keys[moment.id] = moment;
    });
  });
  return keys;
}

So parse the JSON to create an object, then use generateIndex to create an index. You can now pass an ID to the index to get the related object. If you need it as JSON, stringify it:

// data is the JSON parsed to an object
var index = generateIndex(data.moments); 
var id = 2;

console.log(JSON.stringify(index[id]));

/* returns:
   {"id":2,
    "created":"2015-06-10T09:28:59+00:00",
    "updated":"2015-06-10T09:28:59+00:00",
    ...
    "image_id":"5578035a6996d.jpg"
   }
*/

Or if you just want to get a particular moment by ID without generating an index, the following will return the first moment with the matching ID (noting that while arrays will be traversed in index order, objects may not so the "first" may not be the one expected if there are duplicates):

function getById(moments, id) {
  var temp;
  Object.keys(moments).some(function(date) {
    return moments[date].some(function(moment) {
      temp = moment.id == id? moment : temp;
      return temp;
    });
  });
  return temp;
}

getById(data.moments, 4);  
RobG
  • 142,382
  • 31
  • 172
  • 209