Skip to content
Advertisement

Javascript – calling an external function as a property of an object

I have an array of objects, at this moment there is just one object inside. In this object i have a function that elaborate some properties of the same object. The function is processed outside the array, but the result is NaN, i dont know how pass correctly the values..

Example

let arrayObj = [{
  number1: 1,
  number2: 2,
  sum: sum(this.number1 , this.number2)
}
]

function sum(n1, n2) {
  return console.log(n1 + n2);
}

Result: NaN.

for (let i in arrayObj){
  console.log(arrayObj[i])
}

Result: {number1: 1, number2: 2, sum: undefined}

Advertisement

Answer

You can add that property to the object when you are iterating over it.

const arrayObj = [{
    number1: 1,
    number2: 2,
}];

function sum(n1, n2) {
  return n1 + n2;
}

for (let i in arrayObj){
  arrayObj[i].sum = sum(arrayObj[i].number1, arrayObj[i].number2)
  console.log(arrayObj[i])
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement