JSFiddle - React, Tailwind, and code Playground
by Pedro Moreira
JavaScript
var handler = {
get: function(target, property, receiver) {
// console.log(target, property, receiver);
if (!target.length) {
return [];
}
const reflector = target[0][property];
if (typeof reflector === 'function') {
return function() {
return target.map((item) => item[property](...arguments));
}
}
if (property === 'props' && !target.hasOwnProperty(property)) {
return function(...props) {
if (!props.length) {
return {};
}
if (Array.isArray(props[0])) {
props = props[0];
}
return target.map((item) => {
const tuple = {};
props.forEach((key) => {
tuple[key] = item[key];
});
return tuple;
});
}
}
return target.map((item) => item[property]);
}
};
Object.defineProperty(Array.prototype, 'each', {
get: function() {
return new Proxy(this, handler);
}
});
class Animal {
constructor(name) {
this.id = Animal._id++;
this.name = name;
}
say(response) {
return this.name;
}
}
Animal._id = 1;
const cat = new Animal('cat');
const dog = new Animal('dog');
const fox = new Animal('fox');
const array = [cat, dog, fox];
console.log(array.each.say());
console.log(array.each.props('id', 'name'));
console.log(array.map(({
id,
name
}) => {
return {
id,
name
}
}));
// console.log(array.each.say('a ring ding ding'));
// console.log(array.each.name);