简体   繁体   中英

How to convert Json into associative array or key value array

I have following Json which i need to insert into a table. I want to convert each student detail into a row. Because if i loop through the rows as per the existing structure i am reading one column as a row.

var json   {  
       "Students":[  
          {  
             "name":{  
                "value":"Allan"
             },
             "number":{  
                "value":"123"
             }
          },
          {  
             "name":{  
                "value":"Frank"
             },
             "number":{  
                "value":"456"
             }
          }
       ]
    }

Ideally i want to the above as

{ "name": "Allan", "number": 123}; 
{ "name": "Frank", "number": 456}; 

I am looping through the Json as below

var objectKeys = Object.keys(json);
for (var key in objectKeys)
{       

        var student = json.Students;

        for (var i = 0; i < student .length; i++) {

            for (var column in json.Students[i]) {
                window.print(column);
                window.print(json.Students[i][column].value);

            }

        }
    }

NOTE: No JQuery, want to achieve the above through normal Javascript.

If you want to transform the data, you can use Array.map

 var json = {"Students":[{"name":{"value":"Allan"},"number":{"value":"123"}},{"name":{"value":"Frank"},"number":{"value":"456"}}]}; let result = json.Students.map(o => ({ name: o.name.value, number: o.number.value })); console.log(result);

If you want to access the data, you can use Array.forEach

 var json = {"Students":[{"name":{"value":"Allan"},"number":{"value":"123"}},{"name":{"value":"Frank"},"number":{"value":"456"}}]}; json.Students.forEach(o => console.log({name: o.name.value, number: o.number.value}));

No map or reduce. Just classic Javascript.

 var json = { "Students": [{ "name": { "value": "Allan" }, "number": { "value": "123" } }, { "name": { "value": "Frank" }, "number": { "value": "456" } } ] }; for (var student of json["Students"]) { console.log(student); //your logic goes here. }

var json = {  
   "Students":[  
      {  
         "name":{  
            "value":"Allan"
         },
         "number":{  
            "value":"123"
         }
      },
      {  
         "name":{  
            "value":"Frank"
         },
         "number":{  
            "value":"456"
         }
      }
   ]
}

var studentData = JSON.stringify(json.Students);
var convertedData = JSON.parse(studentData.replace(/\{\"value\"\:/g,"").replace(/\}\,\"number/g,',"number').replace(/\"\}\}/g,'"}')); 

Try this :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM