Computer >> Computer tutorials >  >> Programming >> Javascript

Multiply only specific value in a JavaScript object?


Let’s say the following is our object −

var employee =
   [
      { name: "John", amount: 800 },
      { name: "David", amount: 500 },
      { name: "Bob", amount: 450 }
   ]

We need to multiple the “amount” value with 2, only if the amount is greater than 500 i.e. the expected output should be −

[
   { name: 'John', amount: 1600 },
  { name: 'David', amount: 500 },
  { name: 'Bob', amount: 900 }
]

Example

Here is the sample example for multiplying the object values −

var employee =
   [
      { name: "John", amount: 800 },
      { name: "David", amount: 500 },
      { name: "Bob", amount: 450 }
   ]
console.log("Before multiplying the result=")
console.log(employee)
for (var index = 0; index < employee.length; index++) {
   if (employee[index].amount > 500) {
      employee[index].amount = employee[index].amount * 2;
   }
}
console.log("After multiplying the result=")
console.log(employee)

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo257.js.

Output

This will produce the following output on console −

PS C:\Users\Amit\javascript-code> node demo257.js
Before multiplying the result=
[
   { name: 'John', amount: 800 },
   { name: 'David', amount: 500 },
   { name: 'Bob', amount: 450 }
]
After multiplying the result=
[
   { name: 'John', amount: 1600 },
   { name: 'David', amount: 500 },
   { name: 'Bob', amount: 900 }
]