quemeful
quemeful

Reputation: 9848

Is there a way to extend an array of JavaScript objects?

In JavaScript you can extend the functionality of an object with prototype.

Person.prototype.fullName = function () {
    return this.first + this.last;
};

I run into scenarios a lot where I need to process something on an array of specific objects. These are cases where it would be nice for the functionality to be linked to that object type, as opposed to just passing as an array parameter. I am aware that it is unadvised to extend the JavaScript Array.

Is there an equivalent standard to extend the functionality of an array of objects? Here is a pseudo-example of what I mean:

Person(Array).prototype.groupByAges = function () {
    // logic here that would group by ages
    // { '0-15': [person, person], '16-18': [person, person], etc. }

    return list;
};

// could be used like this
const list = persons.groupByAges();

What I have tried:

  1. writing functions like getAgeGroupsByPerson(arr) which end up cluttering code
  2. JQuery.grep() and JavaScript arr.map() which help but does not link the functionality to that specific object type.

Note: I realize that there may be better ways to logically solve the specific age grouping problem that I have described. It is just an example to demonstrate my point. Thank you.

Upvotes: 0

Views: 444

Answers (2)

Henrik Andersson
Henrik Andersson

Reputation: 47172

I see two different approaches that would satisfy your requirements

1) Write a class that extends Array and stick your array in there

class MyArray extends Array {
  groupByAge() {
    console.log(this);
  }
}


let a = MyArray.from([1,2,3]);
a.groupByAge();

2) Write a normal function that takes an array of your objects and does work on it.

function groupByAge(array) {
   console.log(this);
}

There is more work than payoff to try to extend a new Array function IMO than doing both of the above. If JS classes isn't something you can utilize then I'd suggest going for the function and just call that "everywhere".

Upside to both approaches is that they are quite easily testable and that's something that we want.

Upvotes: 2

Ele
Ele

Reputation: 33726

You can decorate your arrays

let decorate = (array) => {
  array.groupByAges = function() {
   console.log(`Grouping = ${this}`);
  }  
  return array;
}

decorate([1,2,3]).groupByAges();

Upvotes: 1

Related Questions