Home > Mobile >  Can't log the key of a object, it's being logged as separate strings in typescript
Can't log the key of a object, it's being logged as separate strings in typescript

Time:05-05

I want to log the key property, but I am getting separate characters:

         let data = [{
                        "mr": 1650886620,
                        "miss": 0.777327955
                    },
                    {
                        "mr": 1650887221,
                        "miss": 0.8514726
                    },
                    {
                        "mr": 165,
                        "miss": 0.8
                    },
                    "properties":{
                        "mr":"value1",
                        "miss":"vl2"
                    }
                    ];
    
    // data.forEach((obj) => {
    //  Object.keys(obj).forEach((key) => {
    //             console.log("key : "   key   " - value : "   obj[key as keyof object]);
    //   });
    // });
    
        data.forEach((obj) => 
        Object.entries(obj).forEach(([i, j]) => 
        console.log(i, j)));

Output:

    [LOG]: "mr",  1650886620 
    [LOG]: "miss",  0.777327955 
    [LOG]: "mr",  1650887221 
    [LOG]: "miss",  0.8514726 
    [LOG]: "mr",  165 
    [LOG]: "miss",  0.85 
    [LOG]: "0",  "p" 
    [LOG]: "1",  "r" 
    [LOG]: "2",  "o" 
    [LOG]: "3",  "p" 
    [LOG]: "4",  "e" 
    [LOG]: "5",  "r" 
    [LOG]: "6",  "t" 
    [LOG]: "7",  "i" 

I have commented out another method, which is giving same kind of output.

CodePudding user response:

you have to fix "properties" of json

var data = [
  {
    mr: 1650886620,
    miss: 0.777327955,
  },
  {
    mr: 1650887221,
    miss: 0.8514726,
  },
  {
    mr: 165,
    miss: 0.8,
  },
  {
    properties: {
      mr: "value1",
      miss: "vl2",
    }
  }
];

and try this code

data.forEach((obj) =>
  Object.entries(obj).forEach(([i, j]) => {
    if (typeof j != "object") console.log(i, j);
    else {
      console.log(i, ":");
      Object.entries(obj[i]).forEach(([y, z]) => console.log(y, z));
    }
  })
);
  • Related