У меня есть следующий пример JSON с массивом под "results", который содержит два объекта. Он может включать в себя сотни объектов в массиве "results" с одинаковыми ключами и разными значениями.
У меня нет доступа для изменения этого файла JSON.
{
"results": [
{
"title": "Information Collection Requests; Direct Loan Servicing-Regular; and Servicing Minor Program Loans",
"type": "Notice",
"abstract": "In accordance with the Paperwork Reduction Act (PRA) requirement, the Farm Service Agency (FSA) is requesting comments from all interested individuals and organizations on a revision of two currently approved information collection requests, Direct Loan Servicing--Regular and Servicing Minor Program Loans, respectively. In the Direct Loan Servicing--Regular, the information is used to determine borrower compliance with loan agreements, assist the borrower in achieving business goals, and regular servicing of the loan account such as graduation, subordination, partial release, use of proceeds, and consent. In Servicing Minor Program Loans, the information collected is used to perform routine and special servicing actions for loans authorized and serviced under FSA's Minor Loan Program.",
"document_number": "2023-05464",
"html_url": "https://www.federalregister.gov/documents/2023/03/17/2023-05464/information-collection-requests-direct-loan-servicing-regular-and-servicing-minor-program-loans",
"pdf_url": "https://www.govinfo.gov/content/pkg/FR-2023-03-17/pdf/2023-05464.pdf",
"public_inspection_pdf_url": "https://public-inspection.federalregister.gov/2023-05464.pdf?1678970722",
"publication_date": "2023-03-17",
"agencies": [
{
"raw_name": "DEPARTMENT OF AGRICULTURE",
"name": "Agriculture Department",
"id": 12,
"url": "https://www.federalregister.gov/agencies/agriculture-department",
"json_url": "https://www.federalregister.gov/api/v1/agencies/12",
"parent_id": null,
"slug": "agriculture-department"
},
{
"raw_name": "Farm Service Agency",
"name": "Farm Service Agency",
"id": 157,
"url": "https://www.federalregister.gov/agencies/farm-service-agency",
"json_url": "https://www.federalregister.gov/api/v1/agencies/157",
"parent_id": 12,
"slug": "farm-service-agency"
}
],
"excerpts": "In accordance with the Paperwork Reduction Act (PRA) requirement, the Farm Service Agency (FSA) is requesting comments from all interested individuals and organizations on a revision of two currently approved information collection requests, Direct..."
},
{
"title": "Notice of Funding Opportunity for the Socially Disadvantaged Groups Grant for Fiscal Year 2023",
"type": "Notice",
"abstract": "This notice announces that the Rural Business-Cooperative Service (RBCS, Agency), a Rural Development (RD) agency of the United States Department of Agriculture (USDA), invites applications for grants under the Socially Disadvantaged Groups Grant (SDGG) program for Fiscal Year (FY) 2023. This notice is being issued to allow applicants sufficient time to leverage financing, prepare and submit their applications, and give the Agency time to process applications within FY 2023. A total of $3,000,000 in grant funding will be available for FY 2023. Successful applications will be selected by the Agency for funding and subsequently awarded to the extent that funding may ultimately be made available through appropriations. All applicants are responsible for any expenses incurred in developing and submitting their applications.",
"document_number": "2023-05441",
"html_url": "https://www.federalregister.gov/documents/2023/03/17/2023-05441/notice-of-funding-opportunity-for-the-socially-disadvantaged-groups-grant-for-fiscal-year-2023",
"pdf_url": "https://www.govinfo.gov/content/pkg/FR-2023-03-17/pdf/2023-05441.pdf",
"public_inspection_pdf_url": "https://public-inspection.federalregister.gov/2023-05441.pdf?1678970718",
"publication_date": "2023-03-17",
"agencies": [
{
"raw_name": "DEPARTMENT OF AGRICULTURE",
"name": "Agriculture Department",
"id": 12,
"url": "https://www.federalregister.gov/agencies/agriculture-department",
"json_url": "https://www.federalregister.gov/api/v1/agencies/12",
"parent_id": null,
"slug": "agriculture-department"
},
{
"raw_name": "Rural Business-Cooperative Service",
"name": "Rural Business-Cooperative Service",
"id": 456,
"url": "https://www.federalregister.gov/agencies/rural-business-cooperative-service",
"json_url": "https://www.federalregister.gov/api/v1/agencies/456",
"parent_id": 12,
"slug": "rural-business-cooperative-service"
}
],
"excerpts": "This notice announces that the Rural Business-Cooperative Service (RBCS, Agency), a Rural Development (RD) agency of the United States Department of Agriculture (USDA), invites applications for grants under the Socially Disadvantaged Groups Grant..."
}
]
}
У меня есть следующий код для получения и отображения нужных мне значений из каждого ключа в массиве:
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
const myArr = JSON.parse(this.responseText);
let text = "";
for (let i in myArr.results) {
text += "<div class='fed-reg-container'><h2 class='title'>" + myArr.results[i].title + "</h2><p>" + myArr.results[i].type + "</p><p>" + myArr.results[i].agencies[0].raw_name + " Document # " + myArr.results[i].document_number + "</p><p>Posted on: " + myArr.results[i].publication_date + "</p><p>" + myArr.results[i].abstract + "</p><a class='fed-reg-button' href='" + myArr.results[i].html_url + "'>Read More</a></div>";
}
text += "";
document.getElementById("demo").innerHTML = text;
};
xmlhttp.open(
"GET",
"https://www.federalregister.gov/api/v1/documents.json?conditions%5Bagencies%5D%5B%5D=agriculture-department&conditions%5Bagencies%5D%5B%5D=federal-highway-administration&conditions%5Bagencies%5D%5B%5D=fish-and-wildlife-service&conditions%5Bagencies%5D%5B%5D=forest-service&conditions%5Bagencies%5D%5B%5D=interior-department&conditions%5Bagencies%5D%5B%5D=international-boundary-and-water-commission-united-states-and-mexico&conditions%5Bagencies%5D%5B%5D=land-management-bureau&conditions%5Bagencies%5D%5B%5D=national-highway-traffic-safety-administration&conditions%5Bagencies%5D%5B%5D=national-park-service&conditions%5Bagencies%5D%5B%5D=reclamation-bureau&conditions%5Bagencies%5D%5B%5D=environmental-protection-agency&conditions%5Bagencies%5D%5B%5D=council-on-environmental-quality&conditions%5Bagencies%5D%5B%5D=safety-and-environmental-enforcement-bureau&conditions%5Bagencies%5D%5B%5D=environment-office-energy-department&conditions%5Bcomment_date%5D%5Bgte%5D=05%2F01%2F2023&conditions%5Bcomment_date%5D%5Blte%5D=01%2F01%2F2050&conditions%5Bterm%5D=arizona&conditions%5Btype%5D%5B%5D=RULE&conditions%5Btype%5D%5B%5D=PRORULE&conditions%5Btype%5D%5B%5D=NOTICE",
true
);
xmlhttp.send();.fed-reg-container {
background-color: black;
color: white;
padding: 20px;
margin: 20px 0;
}
.title {
color: #fcb900;
}
.fed-reg-button {
background-color: #fcb900;
color: black;
padding: 10px;
display: block;
max-width: 100px;
text-align: center;
font-weight: 600;
text-decoration: none;
}<!DOCTYPE html>
<html>
<body>
<p id = "demo"></p>
</body>
</html>Все работает отлично, кроме одного.
Как видите, мой json имеет вложенный массив под "agencies" с несколькими объектами.
Я пытаюсь использовать индексацию, чтобы получить каждое значение под raw_name каждого объекта.
Если я использую + myArr.results[i].agencies[0].raw_name, это работает для одного объекта. Может быть [0] или [1].
Когда я пытаюсь получить второе значение, например + myArr.results[i].agencies[0].raw_name + " - " + myArr.results[i].agencies[1].raw_name, весь код ломается. Я ничего не получаю взамен. Просто белая страница.
Любая идея, что я делаю неправильно?
Спасибо!
for (let j = 0; j < myArr.results[i].agencies.length; j++). Или myArr.results[i].agencies.forEach(agency => ...)это верно только в том случае, если в каждом массиве агентств имеется переменное количество элементов. ваш код не кажется неправильным, просто немного грязным... но компьютер никогда не заботился о беспорядке. Я бы начал с преобразования вашей конкатенации в строку шаблона, чтобы увидеть, есть ли какие-либо неэкранированные символы, искажающие строку.
ААА понятно. Спасибо за быстрый ответ! Можете ли вы привести пример? Я не уверен, куда это поместить. :)
@NicolásStraub Это явно только один пример, нет причин предполагать, что всегда будет 2 агентства.
@NicolásStraub Интересно. Я новичок в JavaScript, поэтому не знаю, как это сделать. Любые указатели? Я проведу небольшое исследование по этому поводу.
конечно, `это строка шаблона с оцененной ${переменной} внутри нее`
@ Бармар, это именно то, что я сказал
@NicolásStraub Кому был адресован ваш комментарий? Я думал, вы предполагаете, что мой цикл for не нужен, потому что всегда есть 2 элемента.
как я уже сказал, это необходимо только в том случае, если у вас есть переменное количество элементов в вашем массиве. поскольку проблема в том, что приложение выдает ошибку, размер массива на самом деле не имеет отношения к вопросу



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Используйте вложенный цикл для обработки всех агентств. Вы можете использовать map(), чтобы перебрать их и вернуть массив имен, и join(), чтобы объединить их с разделителем.
for (let i in myArr.results) {
let agencies = myArr.results[i].agencies.map(a => a.raw_name).join(', ');
text += "<div class='fed-reg-container'><h2 class='title'>" + myArr.results[i].title + "</h2><p>" + myArr.results[i].type + "</p><p>" + agencies + " Document # " + myArr.results[i].document_number + "</p><p>Posted on: " + myArr.results[i].publication_date + "</p><p>" + myArr.results[i].abstract + "</p><a class='fed-reg-button' href='" + myArr.results[i].html_url + "'>Read More</a></div>";
}
Вам нужен вложенный цикл для обработки всех агентств во вложенном массиве.