如何将Json转换为关联数组或键值数组

时间:2018-09-04 09:38:31

标签: javascript arrays json

我有以下Json,需要将其插入表中。 我想将每个学生的详细信息转换为一行。 因为如果我按照现有结构遍历行,则我将一行读为一列。

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

理想情况下,我想以上

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

我正在如下循环遍历Json

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);

            }

        }
    }

注意:没有JQuery,想通过普通的Javascript实现以上目标。

3 个答案:

答案 0 :(得分:0)

如果要转换数据,可以使用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);

如果要访问数据,可以使用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}));

答案 1 :(得分:0)

无图或缩小。只是经典的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.
    }

答案 2 :(得分:0)

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,'"}')); 

尝试一下:)