Problem : I am getting a JSON file i am converting that to an object and looping it in for loop.
But in case of single data i am getting the below:
Eg 1 : Single Data
{ "Id": 2140, “EmpId” : 4732, “Flag”: "No" }
Eg 2 : For Multiple Data i am getting the below:
{ "0": { "Id": 2140, “EmpId” : 4732, “Flag”: "No" }, "1": { "Id": 2141, “EmpId” : 4712, “Flag”: “Yes” } }
When i try to loop that in for loop i get it as undefined for single data ie for Eg 1, for multiple data ie Eg 2 it works fine.
const a = Object.values(data).length;
console.log(a);
for (let i = 0; i < a; i++) {
const res = data[i];
}
Using below code to convert it into JSON
const data = JSON.parse(message.messageText);
How can i handle it in this for loop or how can i make the single data into the below format
{ "0": { "Id": 2140, “EmpId” : 4732, “Flag”: "No" }}
so that it reads the 0 and loops
even tried using object.entries but it reads the id as one and empid as second and so on.
Any help is much appreciated.
Thank You
I tried
const a = object.entries(data)
But it reads the id as one and empid as second and so on.
3
Answers
You can just check whether
0
key exists in the data that you’re receiving. If it exists, that means, you can do your normal loop.Otherwise, you can add a
0
key, and the value will be what you receive in the input.Change
to this:
With this, you check whether if the item
0
exists in the parsed data and just create it if not.