Home > Software design >  Object.keys not printing properly in my code
Object.keys not printing properly in my code

Time:12-28

I am trying to get only keys from the object, but I am getting 0 1 2 3 as output.

Below is my code

data = {"property" : "{\"animalID\": \"12345\", \"animalNumber\" : \"789\", \"type\" : \"mamal\"}"}

onCLick() {
  const dataOne = (JSON.parse(JSON.stringify(this.data)));
  console.log("data", Object.keys(dataOne.property));
}

Below is the current output, which is wrong.

data (61) ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60']

Trying to achieve something like this

const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

console.log(Object.keys(object1));
// expected output: Array ["a", "b", "c"]

CodePudding user response:

You need to parse the JSON string to object as below:

data = {"property" : "{\"animalID\": \"12345\", \"animalNumber\" : \"789\", \"type\" : \"mamal\"}"};

const dataOne = JSON.parse(data["property"]);
console.log("data", Object.keys(dataOne));

  • Related