0

Hellow guys..! I need your help on converting JSON data into an array in javascript. Here below are my codes;

    //---Variable----// 
    JsonData = [{"id":1,"Bus_RegNo":"T 784 DHJ","Name":"Bus1"}];

    BusArray = [];

    //---Converting JSON into an array--//
    StringfiedData = JSON.stringify(JsonData);

    BusArray = JSON.parse(StringfiedData); 

    alert(StringfiedData);

I tried to convert it but when alerting 'BusArray' am getting [object object], I need to get something like;

    {"1","T 784 DHJ","Bus1"}

please help;

  • Your `JsonData` is already an array. If it had quotes wrapping it it would be JSON (a string). `console.log(JsonData[0]);` to see. – Andy May 22 '21 at 09:27
  • The output you specify as `I need to get something like` is not a valid data structure - it is sort of a cross between an array and an object literal – Professor Abronsius May 22 '21 at 09:28
  • 1
    `JsonData` is an array. It's not a JSON string. Your expected output is invalid. If you want to values of the first object inside the array, you need: `Object.values(JsonData[0])`. – adiga May 22 '21 at 09:29
  • Thank you guys, @Professor Abronsius, I actually needed to get a normal array which I can loop through it and get it's element values, so in the question above I should have to write something like this ["1","T 784 DHJ","Bus1"] to mean a normal array. – Ecom Constantine May 22 '21 at 11:42
  • Whatever format it is in you should be able to iterate over it in the way you need to. It is as-easy to iterate over object properties as it is array items - `Object.keys` and `Object.values` both yield iterable arrays – Professor Abronsius May 22 '21 at 12:38
  • Thank you @ Professor Abronsius, I have managed to iterate on it now, using those object functions mentioned above "Object.keys and Object.values". – Ecom Constantine May 22 '21 at 13:36

0 Answers0