Home » Jquery » javascript – How add values in different objects in an array?

javascript – How add values in different objects in an array?

Posted by: admin February 22, 2020 Leave a comment

Questions:

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
  }]
How to&Answer:

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)

Answer:

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