0

This is for an assignment. Please DO NOT down vote. Everybody had to start somewhere, and each person learns differently.

I need to create a function that builds an array consisting solely of the values in any given simpler object: for example: //headache {abd:123, def: 345, ghi: 756} should yield array juice [123, 345, 756];

If I type the object.key 'headache.abd', the console will show the value '123', and using this logic, I attempted to use the 'array.push' function to build a list. Here's my code:

function listAllValues(headache) {
  var juice =[];
  for (var keys in headache){
      juice.push(obj.keys);
  }
  console.log(juice);
}

//But the above code prints out [undefined, undefined, undefined], instead of [123, 345, 756]. Where did I mess up? I feel like I'm close, but I've been unsuccessfully trying various combinations :(, help please.

Joan
  • 13
  • 3

2 Answers2

0

use headache[keys] insteda of obj.keys.

function listAllValues(headache) {
  var juice =[];
  for (var keys in headache){
      juice.push(headache[keys]);
  }
  alert(juice);
}


headache = {abd:123, def: 345, ghi: 756} ;
listAllValues(headache);
Dinesh undefined
  • 5,490
  • 2
  • 19
  • 40
0

Your code has a couple wonky things:

  • It tries to use a obj object, but that doesn't exist

  • You're never using the keys item that the loop gives you

    • It should probably be key instead
  • You're never filtering it using hasOwnProperty which you should always do.

  • You're printing inside the function which is generally regarded as bad

Fixed up code:

function listAllValues(headache) {
  var juice =[];
  for (var key in headache){
        if (headache.hasOwnProperty(key)) {
          juice.push(headache[key]);
       } 
  }
  return juice;
}

console.log(listAllValues({abd:123, def: 345, ghi: 756} ))
Carcigenicate
  • 43,494
  • 9
  • 68
  • 117