-2
let x = {a:1,b:2};
const xarr = [];
for(let i in x){
    xarr.push(i); 
    console.log(i);
}

//output is a, b but I want output 1 and 2.

Thanks in advance

Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
Neha
  • 31
  • 5
  • 1
    Also a similar question: https://stackoverflow.com/questions/20673527/get-value-out-of-an-object-using-a-for-in-loop-in-javascript#20673539 – Nisarg Shah Aug 31 '18 at 07:13
  • Also, `x` is not an array, it is an object. `i` is the property of the object. You can access the values using `x[i]` - as shown in linked duplicates. – Nisarg Shah Aug 31 '18 at 07:16

3 Answers3

1

Simply use Object.values(obj) .Is Return with array format

let x = {a:1,b:2};
var res =Object.values(x);
console.log(res.toString())
prasanth
  • 22,145
  • 4
  • 29
  • 53
0

In your code you need to use x[i] not i for printing

   let x = {a:1,b:2};
    const xarr = [];
    for(let i in x){
             console.log(x[i]);

     xarr.push(x[i]); 
    }
    
         console.log(xarr);
Rupesh Agrawal
  • 645
  • 8
  • 22
0

A for loop in javascript will iterate over the keys of an object, if you want the values you will have to fetch then om the object using that key.

let x = {a:1,b:2};
const xarr = [];
for(let i in x){
 xarr.push(x[i]); 
 console.log(x[i]);
}
Jerodev
  • 32,252
  • 11
  • 87
  • 108