我想使用 JavaScript 访问此 JSON 对象的所有键和值

i want to access all keys and values of this json objects using javascript

本文关键字:对象 键和值 JSON JavaScript 访问      更新时间:2023-09-26
<!DOCTYPE html>
<html>
<body>
<p>employees var having the json array n objects</p>
<p id="demo"></p>
<script>
var employees = [{
    "_id": "P_00001",
    "Product": "SEA EXPORT",
    "Status": "Active",
    "Origin": "JEBEL ALI(DUBAI), United Arab Emirates (AEJEA)",
    "Destination": "CHENNAI, India (INMAA)",
    "CreatedDate": "2016-01-13T07:17:05.251Z"
}];
for( i=0 ; i < employees.length ; i++ )
{
    document.getElementById("demo").innerHTML +="<br/>" + employees[i]["_id"] + " " + employees[i][key()];
}
</script>
</body>
</html>
  • 具有存储在 VAR 员工的键和值的 JSON 对象
  • 我不知道如何使用forloop显示对象的键和值
可以使用

for/in 循环访问对象中的所有键,然后使用该键访问值:

var txt = "";
var person = {fname:"John", lname:"Doe", age:25}; 
var x;
for (x in person) {
    txt += person[x] + " ";
}
alert(txt);

http://www.w3schools.com/js/tryit.asp?filename=tryjs_object_for_in

编辑 1

此函数突出显示键和值:

var employees = [{
    "_id": "P_00001",
    "Product": "SEA EXPORT",
    "Status": "Active",
    "Origin": "JEBEL ALI(DUBAI), United Arab Emirates (AEJEA)",
    "Destination": "CHENNAI, India (INMAA)",
    "CreatedDate": "2016-01-13T07:17:05.251Z"
}];
for( var e of employees ) {  
  for( var key in e ) {
      alert('The key "'+ key + '" represents the value "' + e[key] + '"')
  }
}

你可以:

for(i in employees){
    var key = i;
    var val = employees[i];
    for(j in val){
        var sub_key = j;
        var sub_val = val[j];
        document.getElementById("demo").innerHTML +="<br/>" + (sub_key) + " " + sub_val;
    }
}

小提琴