正在从 javascript 中数组的数组列表中获取 JSON 数据
Fetching JSON data from array's array list in javascript
我正在使用 JSON 从 json 文件中存储和检索一些值。我正在尝试使用 javascript 获取 JSON 数据。 JSON 数据在数组列表中有数组。我能够获取对象列表但无法获取内部数组。下面是我的 JSON 数据及其格式。
我错过了什么?
artifacts.json
{
"artifacts": [
{
"technology": "Agile Software Development",
"techBasedArtifacts": [
{
"title": "Agile 1",
"artifactLink": "https://www.google.com/"
},
{
"title": "Agile 2",
"artifactLink": "https://www.google.com/"
}
]
},
{
"technology": "UI Development",
"techBasedArtifacts": [
{
"title": "UI 1",
"artifactLink": "https://www.google.com/"
},
{
"title": "UI 2",
"artifactLink": "https://www.google.com/"
}
]
}
]
}
app.js
"use-strict";
let requestURL = "./artifacts.json";
let request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'text';
request.send();
request.onload = () => {
const a = request.response;
const b = JSON.parse(a);
console.log(b.artifacts) //Shows object array which is good
console.log(b.artifacts.techBasedArtifacts) // Shows undefined
}
IMO artifacts 是一个数组,而不是一个对象。您正在从对象访问“techBasedArtifacts”字段:
console.log(b.artifacts[0].techBasedArtifacts);
如果你想获取特定索引的 techBasedArtifacts 那么你可以使用 like
console.log(b.artifacts[0].techBasedArtifacts)
您可以访问第0个索引的子数组。
如果你想得到所有索引的所有techBasedArtifacts,那么你必须迭代数组并将所有techBasedArtifacts合并到一个数组中。
var result = b.artifacts.map(x => x.techBasedArtifacts).reduce((x, y) => { return x = [...x, ...y];})
console.log(result); // will give you merged result set.
我正在使用 JSON 从 json 文件中存储和检索一些值。我正在尝试使用 javascript 获取 JSON 数据。 JSON 数据在数组列表中有数组。我能够获取对象列表但无法获取内部数组。下面是我的 JSON 数据及其格式。 我错过了什么?
artifacts.json
{
"artifacts": [
{
"technology": "Agile Software Development",
"techBasedArtifacts": [
{
"title": "Agile 1",
"artifactLink": "https://www.google.com/"
},
{
"title": "Agile 2",
"artifactLink": "https://www.google.com/"
}
]
},
{
"technology": "UI Development",
"techBasedArtifacts": [
{
"title": "UI 1",
"artifactLink": "https://www.google.com/"
},
{
"title": "UI 2",
"artifactLink": "https://www.google.com/"
}
]
}
]
}
app.js
"use-strict";
let requestURL = "./artifacts.json";
let request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'text';
request.send();
request.onload = () => {
const a = request.response;
const b = JSON.parse(a);
console.log(b.artifacts) //Shows object array which is good
console.log(b.artifacts.techBasedArtifacts) // Shows undefined
}
IMO artifacts 是一个数组,而不是一个对象。您正在从对象访问“techBasedArtifacts”字段:
console.log(b.artifacts[0].techBasedArtifacts);
如果你想获取特定索引的 techBasedArtifacts 那么你可以使用 like
console.log(b.artifacts[0].techBasedArtifacts)
您可以访问第0个索引的子数组。
如果你想得到所有索引的所有techBasedArtifacts,那么你必须迭代数组并将所有techBasedArtifacts合并到一个数组中。
var result = b.artifacts.map(x => x.techBasedArtifacts).reduce((x, y) => { return x = [...x, ...y];})
console.log(result); // will give you merged result set.