Reputation: 25
I have an array of javascript objects, and I want to create a key:value pair that is the product of two values.
I can solve this using much longer code outside of the object (i.e. in a 'for each' loop), but I thought there must be an easier way. Perhaps you could point me to the right direction?
let DB = [
{
number: 100,
factor: 1.5
product: this.number * this.factor // doesn't work :(
},
{
...
}
];
I want product to equal 150, which is 100 * 1.5, but I don't know how to get access to those 2 values.
Upvotes: 0
Views: 8174
Reputation: 1
if you want to do the calculation inside the object, you can try using a getter as documented here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get
x = {
number: 100,
factor: 1.5,
get product() { return this.number * this.factor}
}
console.log(x.product)
Upvotes: 0
Reputation: 22320
or simply: (because map method creates a new array, otherwise use forEach method)
let DB = [ { number: 100, factor: 1.5 }
, { number: 100, factor: 1.2 }
];
for (let db of DB ) { db.product = db.number * db.factor }
/// verify =
for (let db of DB ) console.log( JSON.stringify(db))
Upvotes: 0
Reputation: 34248
you cant do it inside the array, but its easy enough to solve using map.
[ { number: 100, factor: 1.5}].map(element => ({...element, product: element.number * element.factor}));
.map()
goes through the array and makes a new one with each element being the result of the function passed in.
The ...
is spread, it takes all of the properties in the original object and puts them onto the new object you are making.
Upvotes: 1