Utilizing the inherent Array type in JavaScript, it seems that achieving this can be closest by using Object.assign
to duplicate named properties from an object to an Array object. However, there is uncertainty if this approach will yield the expected results.
const a = Object.assign([1,2,3], {a:4, b:5, c:6});
This method works because an array functions as an object of a distinct kind, equipped with specific Array.prototype
functionalities for managing its numerically indexed elements.
If the intention was to iterate over non-numeric named properties using operations like .map
or .forEach
, it won't succeed. These methods are tailored for working solely with numerically indexed array items. Trying them with the aforementioned array yields:
a.forEach(x=> console.log(x));
// output:
// => 1
// => 2
// => 3
The properties a/b/c
aren't displayed.
A more effective solution, likely aligning with your intentions, involves creating a custom "class," such as demonstrated below:
function NamedArray(init) {
Object.assign(this, init);
}
NamedArray.prototype.forEach = function(callback) {
const keys = Object.entries(this);
keys.forEach(([key, value],array)=> callback(value, key, array));
}
const arr = new NamedArray({a:1,b:2,c:3});
arr.forEach((value,key)=> {
console.log(key, value);
})
You can define all necessary class methods using this structure.
Note: There is also ES6 syntax available for generating these classes, which streamlines the creation of objects featuring numerous prototype methods and properties.