Nen*_*ski 5 javascript arrays json object
我怎样才能从JSON文件中获取名称.此外,代码完全适用于从"file.json"获取数据,即这不是问题.
JavaScript的:
var data = [];
function getName() {
//what should I write here to get only name from the first object i.e. John
//with this: data[0].name I am getting error!
}
var xhttp;
if(window.XMLHttpRequest)
xhttp = new XMLHttpRequest();
else
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4) {
data = JSON.parse(xhttp.responseText);
getName();
}
}
xhttp.open("GET","file.json",true);
xhttp.send();Run Code Online (Sandbox Code Playgroud)
"file.json" - JSON:
[
{
"name":"John",
"city":"London"
},
{
"name":"Maria",
"city":"Rome"
}
]Run Code Online (Sandbox Code Playgroud)
通过函数传递变量数据
var data = [];
function getName(data) {
return data[0].name;
}
var xhttp;
if(window.XMLHttpRequest)
xhttp = new XMLHttpRequest();
else
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4) {
data = JSON.parse(xhttp.responseText);
getName(data);
}
}
xhttp.open("GET","file.json",true);
xhttp.send();
Run Code Online (Sandbox Code Playgroud)
此外,如果要检索所有名称,可以执行以下操作:
function getName(data) {
var names = [];
for (var i = 0; i < data.length; i++) {
names.push(data[i].name);
}
return names;
}
Run Code Online (Sandbox Code Playgroud)
(数据是数组数据)
使用Array.prototype.map()来转换数组的项:
data.map(function(item) {
return item.name
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9327 次 |
| 最近记录: |