How do i define an array object with a propery that will be emitted when using a spread operator, if such thing is even possible (and why if it is not?).
I'm using arrays in a redux app so when I'm updating a store with a return {...state,newElement}
i lose the properties of the arrays in my state.
for example:
const object1 = [1,2,3];
Object.defineProperty(object1, 'pizza', {
value: 30,
writable: true,
enumerable:true,
configurable:true
});
console.log(...object1);
// output: 1 2 3
// my expected output: 1 2 3 30
thanks
The actual iterator of your hybrid object-array is the Array's one (which is Array.prototype.values
):
const arr = []; console.log(arr.values === arr[Symbol.iterator])
If you want to have an hybrid object-array, and expect it to be fully iterable, you have to write the iterator yourself in order to override the Array's one:
const object1 = [1,2,3]; Object.defineProperty(object1, 'pizza', { value: 30, writable: true, enumerable:true, configurable:true }); object1[Symbol.iterator] = function* () { // Write whatever implementation you need for(const key in this) { yield this[key]; } } console.log(...object1); // output: 1 2 3 30
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.