0

How can I access only the first @NOTIFICATION_OPENED key?

How can I sum both values of @NOTIFICATION_OPENED?

This is my AJAX request:

$.getJSON("myapiurl", function(notificationData) {
  $.each(notificationData.data, function(index, value) {
    if (value["@NOTIFICATION_OPENED"]) {
      var notificationOpened = value["@NOTIFICATION_OPENED"]
    } else 
      notificationOpened = 0;

    var val = {
      "notificationOpened": notificationOpened
    }
    _data.push(val)
  });
}

This is the data I retrieve from the API using the above request:

{
  "data": [{
    "date": 1577836800000,
    "@NOTIFICATION_SENT": 62629,
    "@NOTIFICATION_OPENED": 404
  }, {
    "date": 1577923200000,
    "@NOTIFICATION_OPENED": 734
  }]
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Phil Jones
  • 37
  • 6
  • 1
    Does this answer your question? [How can I access and process nested objects, arrays or JSON?](https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json) – Heretic Monkey Feb 20 '20 at 14:50

2 Answers2

1

How can I access only the first @NOTIFICATION_OPENED key?

Simply take the first element of data, and then take the value of @NOTIFICATION_OPENED. for example:

var notification = {
    "data": [{
        "date": 1577836800000,
        "@NOTIFICATION_SENT": 62629,
        "@NOTIFICATION_OPENED": 404
    }, {
        "date": 1577923200000,
        "@NOTIFICATION_OPENED": 734
    }]
}

var firstNotificationData = notification.data[0]
var firstNotificationOpenedData = firstNotificationData["@NOTIFICATION_OPENED"]
console.log(firstNotificationOpenedData)

How can I sum both values of @NOTIFICATION_OPENED?

You can use reduce to summarize the total of notification opened. for example:

var notification = {
    "data": [{
        "date": 1577836800000,
        "@NOTIFICATION_SENT": 62629,
        "@NOTIFICATION_OPENED": 404
    }, {
        "date": 1577923200000,
        "@NOTIFICATION_OPENED": 734
    }]
}

var totalNotificationOpened = notification.data.reduce(function (acc, d) {
    return acc + d["@NOTIFICATION_OPENED"]
}, 0)

console.log(totalNotificationOpened)
novalagung
  • 10,905
  • 4
  • 58
  • 82
-2

I have added a square bracket to make it valid JSON:

const data = 
[
  {
    "date": 1577836800000,
    "@NOTIFICATION_SENT": 62629,
    "@NOTIFICATION_OPENED": 404
  },
  {
   "date": 1577923200000,
   "@NOTIFICATION_OPENED": 734
  }
 ]

let nSent   = data[0]["@NOTIFICATION_SENT"]
let nOpened = data[0]["@NOTIFICATION_OPENED"]
let mySum   = nSent+nOpened

alert(mySum)

This will produce an alert with the sum 63033

unit303
  • 71
  • 7