0

I have some JSON data that will look something like this:

   {
  "events": [
    {
      "event": {
        "event_instances": [
          {
            "event_instance": {
              "id": 1365348,
              "ranking": 0,
              "event_id": 460956,
              "start": "2015-07-07T00:00:00-05:00",
              "end": null,
              "all_day": true
            }
          }
        ],
        "id": 460956,
        "title": "Blue Star Museums",
        "url": "http:\/\/www.samhoustonmemorialmuseum.com\/",
        "updated_at": "2015-07-07T05:27:49-05:00",
        "created_at": "2015-06-02T12:34:01-05:00",
        "facebook_id": null,
        "first_date": "2015-06-02",
        //so on and so forth

I'm need to use that first_date key value in a jQuery conditional that will basically say something like this:

if(first_date.value().substring(0,3) === 2015){
    //do something
}

Can you use substrings of key values for conditionals in jQuery?

3
  • try using var object = $.parseJSON(jsonString) and then you can use object.events and so on.. Commented Jul 7, 2015 at 17:30
  • 1
    Notice that with === you may want to use strings on both sides (i.e.: "2015" === 2015 returns false). Commented Jul 7, 2015 at 17:47
  • @Armfoot nice catch. Noted Commented Jul 7, 2015 at 17:48

2 Answers 2

3

You could do something like this:

var year = MyJSON.events[0].event.first_date.substring(0,4);

if ( year === '2015' ) { ... }
Sign up to request clarification or add additional context in comments.

Comments

2

So assuming that that json is assigned to some variable named jsonVariable

var first_date = jsonVariable.events[0].event.first_date;
var first_date_year = first_date.substring(0,4);

if (first_date_year === '2015') {
    // do somethang
}

How to access first_date

First to access first_date you have to access the array events, the first element of that array (using the index [0]), then the event property, and finally its sub property first_date

How to take the substring

To take the substring you need to use substr(0,4) because the second parameter is the length in characters of the substring not the index position to end it.

How to compare years

Then to compare the substring with 2015 you need to wrap the 2015 in quotes to convert it to a string, or use parseInt() to convert the substring to an integer.

Note: You could also split the string at - and use the first element

var first_date = jsonVariable.events[0].event.first_date;
var first_date_year = first_date.split('-').pop(); // ["2015", "06", "02"] pop the first value

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.