0

when i execute following code:

var myObj = 
  
{
    "name": "moose",
    "age": "22",
    "friends": "0",
  
};
for (x in myObj) {
    console.log(x);     
}

I get following output: {"name":"moose","age":"22","friends":"0"}

But I only want the values, in order to stringify them afterwards. I tried console.log(Object.values(x)) but it didnt work out. Desired output: moose, 22, 0

Thanks in Advance

Thomas Sablik
  • 16,127
  • 7
  • 34
  • 62
lightyears99
  • 101
  • 7
  • _"I get following output: `{"name":"moose","age":"22","friends":"0"}`"_ That's not true as you can see in the interactive code in your question. – Thomas Sablik Feb 27 '21 at 23:00

2 Answers2

1

To iterate through all the keys of a JS Object, use the below syntax:

for (var key in myObj) {
    if (myObj.hasOwnProperty(key)) {
        console.log(key);
      }
 }

So that you can print your values as requested with:

var myObj = 
  
{
"name": "moose",
"age": "22",
"friends": "0",
  
};

for (var key in myObj) {
    if (myObj.hasOwnProperty(key)) {
        console.log(myObj[key]);
      }
 }
BiOS
  • 2,282
  • 3
  • 10
  • 24
0

You have to access your object with x key to access x value:

myObj[x]:

var myObj = {
    "name": "moose",
    "age": "22",
    "friends": "0", 
};

for (x in myObj) {
    console.log(myObj[x]);     
}
sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35