How to add a property through a loop, passing through an array of objects, to set a getter and a setter for each object?

'use strict'; var positions = [ { title: 'Телепорт бытовой VZHIH-101', price: 10000, discount: 7, available: 3 }, { title: 'Ховерборд Mattel 2016', price: 9200, discount: 4, available: 14 }, { title: 'Меч световой FORCE (синий луч)', price: 57000, discount: 0, available: 1 } ]; // exercise - 2 console.log('//==========================\\'); for (let i = 0; i < positions.length; i++) { positions[i].finalPrice = 'new val'; } console.log(positions); 

    1 answer 1

    Use the Object.defineProperty method, if you understand the essence of the task correctly, you should get something like this:

     'use strict'; var positions = [ { title: 'Телепорт бытовой VZHIH-101', price: 10000, discount: 7, available: 3 }, { title: 'Ховерборд Mattel 2016', price: 9200, discount: 4, available: 14 }, { title: 'Меч световой FORCE (синий луч)', price: 57000, discount: 0, available: 1 } ]; // exercise - 2 console.log('//==========================\\'); for (let i = 0; i < positions.length; i++) { Object.defineProperty(positions[i], 'finalPrice', { enumerable: true, get() { return this.price * (100 - this.discount) / 100; }, set(newFinalPrice) { this.price = newFinalPrice / (100 - this.discount) * 100; } }); } console.log(positions);