0

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.

4
  • 2
    let DB = [ { number: 100, factor: 1.5 }, { ... } ].map( o => ({ ...o, product: o.number * o.factor }) ); Commented Jun 18, 2019 at 2:22
  • All the objects have properties number and factor and you want to add a new one callled product as described (= number * factor)? Commented Jun 18, 2019 at 2:22
  • @PatrickRoberts haha snap Commented Jun 18, 2019 at 2:23
  • For a reference: .map(), but I suggest exploring the other array methods in the left navigation bar - there's lots of useful stuff there. Commented Jun 18, 2019 at 2:24

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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))

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.