skip to Main Content

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


  1. 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.

    function read(data){
      if(data?.[0]){
         const a = Object.values(data).length;    
         for (let i = 0; i < a; i++) {
           const res = data[i]
         }
      } else{
        const tempData = {}
        tempData[0] = data
        console.log(tempData)
      }
    } 
    
    Login or Signup to reply.
  2. Change

    const data = JSON.parse(message.messageText);`
    

    to this:

    const parsed = JSON.parse(message.messageText);
    const data = parsed[0] ? parsed : { 0: parsed };
    

    With this, you check whether if the item 0 exists in the parsed data and just create it if not.

    Login or Signup to reply.
  3. let data={ "0":  {     "Id": 2140,     "EmpId" : 4732,     "Flag": "No"   }, "1":  {     "Id": 2141,     "EmpId" : 4712,     "Flag": "Yes"   } }
    
    const a = Object.values(data).length;
    console.log(a);
    
    Object.keys(data).forEach((k, i) => { 
       console.log(i, data[k]);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search