I'm trying to destructure an object with ES6 syntax then reassign the variable inside a loop.
ES5
this.playlist.forEach((item, i) => {
item.timeoutId = setTimeout(() => {
item.sound.play()
}, 1000 * i)
})
ES6 (not working)
this.playlist.forEach(({sound, timeoutId}, i) => {
timeoutId = setTimeout(() => {
sound.play()
}, 1000 * i)
})
Any idea of why it is not working?
It should work, with one caveat:
timeoutId = setTimeout(() => {
sound.play()
}, 1000 * i)
timeoutId
is the value inside item.timeoutId
, and not an alias of it. When you assign a value to timeoutId
, it won't be assigned back to item.timeoutId
.
Using item.timeoutId
to cancel the timeout, won't work, since the item.timeoutId
won't contain the timeout id.
In the example, you can see that timeoutId
stays null
:
const arr=[{ id: 1, timeoutId: null }, { id: 2,timeoutId: null }, { id: 3, timeoutId: null }, { id: 4, timeoutId: null }];
arr.forEach(({sound, timeoutId}, i) => {
timeoutId = setTimeout(() => {
//sound.play()
}, 1000 * i)
})
console.log(arr);
The solution as noted by @guest271314 is to assign to the property directly, using the the 3rd parameter of the forEach
(the array), and the index:
const arr=[{ id: 1, timeoutId: null }, { id: 2,timeoutId: null }, { id: 3, timeoutId: null }, { id: 4, timeoutId: null }];
arr.forEach(({sound}, i, arr) => {
arr[i].timeoutId = setTimeout(() => {
//sound.play()
}, 1000 * i)
})
console.log(arr);
It doesn't work because your ES6 code is basically an equivalent to this code:
this.playlist.forEach((item, i) => {
let timeoutId = item.timeoutId;
let sound = item.sound;
timeoutId = setTimeout(() => {
sound.play()
}, 1000 * i)
})
So you are just reassigning a local variable instead of an item
object property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With