ua_boaz ua_boaz - 4 months ago 9
Javascript Question

underscore loop over array of objects modify certain objects and remove some objects

suppose i have array of objects,

[{"month":"03-2016","isLate":"N","transactionCount":4,"transactionAmount":8746455},{"month":"05-2016","isLate":"N","transactionCount":5,"transactionAmount":-40004952945.61},{"month":"06-2016","isLate":"N","transactionCount":1,"transactionAmount":100000},{"month":"04-2016","isLate":"N","transactionCount":6,"transactionAmount":-117189.89},{"month":"02-2016","isLate":"N","transactionCount":4,"transactionAmount":-5331000},{"month":"04-2016","isLate":null,"transactionCount":2,"transactionAmount":-4888.89},{"month":"03-2016","isLate":null,"transactionCount":3,"transactionAmount":5000}]


is there a function in underscore or javascript where i can loop over the item, based on some condition, remove certain objects, else modify object (add some more information into objects) and return data.

Answer

You can with plain JavaScript:

  • remove certain objects: with filter()
  • modify objects (add some more information into objects): with map()

For example:

var input = [
  {
    "month": "03-2016",
    "isLate": "N",
    "transactionCount": 4,
    "transactionAmount": 8746455
  },
  {
    "month": "05-2016",
    "isLate": "N",
    "transactionCount": 5,
    "transactionAmount": -40004952945.61
  },
  {
    "month": "06-2016",
    "isLate": "N",
    "transactionCount": 1,
    "transactionAmount": 100000
  },
  {
    "month": "04-2016",
    "isLate": "N",
    "transactionCount": 6,
    "transactionAmount": -117189.89
  },
  {
    "month": "02-2016",
    "isLate": "N",
    "transactionCount": 4,
    "transactionAmount": -5331000
  },
  {
    "month": "04-2016",
    "isLate": null,
    "transactionCount": 2,
    "transactionAmount": -4888.89
  },
  {
    "month": "03-2016",
    "isLate": null,
    "transactionCount": 3,
    "transactionAmount": 5000
  }
];

// Helper array to translate month number to month name 
var monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];

input = input
    // only get the entries which don't have isLate=N:
    .filter( o => o.isLate !== 'N' )
    // add a property "mm":
    .map( o => Object.assign(o, { mm: monthNames[+o.month.substr(0,2)-1] }) );

// Output result
console.log(input);