1
var obj = {a: 1, b: 2, c:3}    

Object.keys(obj).forEach(function(x){
    console.log(obj[x])
})

This gives: 1 2 3

so how can I make it to work give me 1 4 9 (e.g. times by itself) I thought this would work

Object.keys(obj).forEach(function(x){
    console.log(obj[x*x])
})
4
  • why dont you use array??? Commented Dec 16, 2016 at 15:49
  • 1
    that would try to take the ninth value, try something like obj[x]*obj[x] Commented Dec 16, 2016 at 15:49
  • 1
    use Math.pow console.log(Math.pow(obj[x], 2)); Commented Dec 16, 2016 at 15:51
  • Possible duplicate of Iterating over objects in Javascript Commented Dec 16, 2016 at 17:01

4 Answers 4

3

you need to multiply the values.

you have x*x which would be 'a'*'a' results in NaN.

obj[NaN] = undefined

var obj = {a: 1, b: 2, c:3}

Object.keys(obj).forEach(function(x){
    console.log(obj[x] * obj[x])
})

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

Comments

0

You're almost there. this one does the job:

Object.keys(obj).forEach(function(x){
    console.log(obj[x]*obj[x])
 })

Comments

0

you can use Object.values in ES2016

Object.values(obj).forEach(function(x){
   console.log(x*x);
})

Comments

0

var obj = {a: 1, b: 2, c:3}

Object.keys(obj).forEach(function(x){
    console.log(Math.pow(obj[x], 2));
})

Math.pow (x,y) => xxx*...y times...*x

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.