A1RStack A1RStack -3 years ago 108
AngularJS Question

Add attribute to specific objects in an array

In AngularJS/Javascript i have an array of objects, these objects contain a date. I want to order these objects by date and add an attribute to the last object with a specific datetime. So if 2 objects have the same date i want to add the attribute to the one with the latest time. If there is only one object with one date i want to add the attribute to that object.

An example:

input: var arr = [
{A: {"Date": "2017-08-14T15:15:00"} B:{}}
{A: {"Date": "2017-08-14T16:15:00"} B:{}} //<--- Add attribute to this object

output: var arr = [
{A: {"Date": "2017-08-14T15:15:00"} B:{}}
{A: {"Date": "2017-08-14T16:15:00"} B:{} C:{"NewAttribute": "true"}}

How do i go about programming this? Originally i was thinking about using a for loop to compare all the objects with each other but i have no idea how to implement it.

Answer Source

I hope I understood what you want:

var arr = [
  {A: {"Date": "2017-08-14T15:15:00"}, B:{}}, // won't get the new property
  {A: {"Date": "2017-08-14T16:12:00"}, B:{}}, // will get the new property
  {A: {"Date": "2017-08-14T15:15:00"}, B:{}}, // will get the new property
  {A: {"Date": "2017-08-14T16:14:00"}, B:{}}, // won't get the new property
  {A: {"Date": "2017-08-14T16:14:00"}, B:{}}  // will get the new property

// sort the array by date in descending order
var sorted = arr.sort(({A: { Date: d1 }}, {A: { Date: d2 }}) => new Date(d2).getTime() - new Date(d1).getTime());

// eventually add the new property
sorted.reduce((acc, o) => {
  var date = o.A.Date;
  if (acc !== date) {
    // the date isn't equal to the date of the last item, so it's
    // either the only item with that date
    // or the first (in reversed order) item with that date
    o.C = {"NewAttribute": "true"};
  return date;
}, '');

// reverse the array
var result = sorted.slice().reverse();


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download