在 JavaScript 的 forEach 循环中通过 Index 从 json API 获取对象值?
get a object value from a json API by Index in a forEach loop in JavaScript?
我正在努力学习如何使用 fetch()
API 这个周末...
我看到了这个有趣的 API 服务,我试着学习如何使用这个
我遇到了一个小问题,javascript
问题
我想从 .Json
获取数据(这很好用),
但是当我想将值放入 <div>
并且到达 object[index]
时没有显示任何内容
据我所知,这似乎是可能的,
但在这种情况下,不是(...我在互联网上到处搜索,没有结果)
基本上...
这个不工作object[index]; //index variable, is a number
这有效 object.object1; //normal method
我试过的
是的,我尝试了使用 obj1.obj2
的传统方法并且工作正常,得到了我想要的结果!
but is not efficient, like I want.
因为我想通过 index
获取值
并将值放入 <div>
与index
的NodeListOf<element>
完整代码,我写的
open the snippet to see the code
let orarioText = document.querySelectorAll('.orario');
const fetchPreghieraTime = async() => {
const data = await fetch('http://api.aladhan.com/v1/timingsByCity?city=Milano&country=Italy&method=8');
const orarioJson = await data.json();
const orario = orarioJson.data.timings;
orarioText.forEach((item, index) => {
item.textContent = orario[index];
console.log(item.textContent + "" + index);
});
}
fetchPreghieraTime();
<div class="container">
<div class="tempo-preghiera-container">
<!-- 1 -->
<div class="tempo-fajr">
<div class="nome-preghiera">fajr</div>
<div class="orario">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
<!-- 2 -->
<div class="tempo-duhr">
<div class="nome-preghiera">duhr</div>
<div class="orario">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
<!-- 3 -->
<div class="tempo-asr">
<div class="nome-preghiera">asr</div>
<div class="orario">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
<!-- 4 -->
<div class="tempo-maghrib">
<div class="nome-preghiera">maghrib</div>
<div class="orario">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
<!-- 5 -->
<div class="tempo-isha">
<div class="nome-preghiera">isha</div>
<div class="orario">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
</div>
</div>
<script src="./script.js"></script>
高效是什么意思?
- 这是编写更少、更简单代码的想法:
elementClass.forEach((item, index) => {
item.textContent = object[index];
});
- 你可以看到下面的方法是多么低效,那是有效的
elementClass[0].textContent = object.Fajr;
elementClass[1].textContent = object.Dhuhr;
elementClass[2].textContent = object.Asr;
elementClass[3].textContent = object.Maghrib;
elementClass[4].textContent = object.Isha;
如果可以,我想要 更少的代码,或者更简单的解决方案
( 我不希望你给出一个可能更快的程序,不不,对我来说如果是简单的逻辑就足够了 )
(考虑如果有 50 个项目,我是否需要写出对象的所有名称,等等...,这就是原因)
我想到第一个想法是因为 数组...
在数组中,您可以使用带数字的括号,以 0 开头,即(无效)
问题
- 代码无效
let orarioText = document.querySelectorAll('.orario');
//there are 5 elements with the same class
orarioText.forEach((item, index) => {
item.textContent = orarioJson.data.timings[index];
});
- 这很好用
let orarioText = document.querySelectorAll('.orario');
//there are 5 elements with the same class
orarioText.forEach((item, index) => {
item.textContent = orarioJson.data.timings.Fajr; //here you see the [index] is replaced by the actual name
});
如果你也想试试,这是我用的API
here is the API service link, I used
http://api.aladhan.com/v1/timingsByCity?city=Milano&country=Italy&method=8
这是它的样子:
{"code":200,"status":"OK","data":{"timings":{"Fajr":"05:31","Sunrise":"07:19","Dhuhr":"12:37","Asr":"15:26","Sunset":"17:56","Maghrib":"17:56","Isha":"19:26","Imsak":"05:21","Midnight":"00:37"}
如有不明白的问题给您:
你可以写评论,询问更多信息,我会回答:)
我所问内容的简短摘要
我想要这个 HTML
<!-- 0 -->
<div class="myClass"></div>
<!-- 1 -->
<div class="myClass"></div>
<!-- 2 -->
<div class="myClass"></div>
<!-- 3 -->
<div class="myClass"></div>
<!-- 4 -->
<div class="myClass"></div>
在JS
之后变成这样HTML
<!-- 0 -->
<div class="myClass">obj1 value</div>
<!-- 1 -->
<div class="myClass">obj2 value</div>
<!-- 2 -->
<div class="myClass">obj3 value</div>
<!-- 3 -->
<div class="myClass">obj4 value</div>
<!-- 4 -->
<div class="myClass">obj5 value</div>
我希望有一个很棒的乐于助人的开发者,
谁有更多的经验,
可以帮助我
(也帮助看到这个问题的未来开发者)
感谢所有社区!
您可以从父元素中获取您需要的 属性 名称。它的 class 名称为“tempo-....”。它只需要更改 HTML,因为您对 dhurh 使用了不同的拼写。因此,请将其与 JSON 响应中的拼写对齐。
以下是如何从“速度”中提取该名称class,然后使用它从响应对象访问时间:
- 查找具有
.parentNode
的父元素
- 用
.className
获取class
属性值
- 使用
.match
和返回数组中的第一个条目提取“tempo-”之后的部分
- 将第一个字母转换为大写,其余字母转换为小写。
- 作为动态使用属性
let orarioText = document.querySelectorAll('.orario');
const fetchPreghieraTime = async() => {
const data = await fetch('http://api.aladhan.com/v1/timingsByCity?city=Milano&country=Italy&method=8');
const orarioJson = await data.json();
const orario = orarioJson.data.timings;
orarioText.forEach((item, index) => {
let name = item.parentNode.className.match(/(?<=\btempo-)\w+/)[0];
item.textContent = orario[name[0].toUpperCase() + name.slice(1).toLowerCase()];
});
}
fetchPreghieraTime();
<div class="container">
<div class="tempo-preghiera-container">
<!-- 1 -->
<div class="tempo-fajr">
<div class="nome-preghiera">fajr</div>
<div class="orario">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
<!-- 2 -->
<div class="tempo-dhuhr">
<div class="nome-preghiera">duhr</div>
<div class="orario">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
<!-- 3 -->
<div class="tempo-asr">
<div class="nome-preghiera">asr</div>
<div class="orario ">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
<!-- 4 -->
<div class="tempo-maghrib">
<div class="nome-preghiera">maghrib</div>
<div class="orario">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
<!-- 5 -->
<div class="tempo-isha">
<div class="nome-preghiera">isha</div>
<div class="orario">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
</div>
</div>
<script src="./script.js"></script>
试试这个
<div class="container">
<div class="tempo-preghiera-container">
</div>
</div>
const fetchPreghieraTime = async () => {
const data = await fetch(
"http://api.aladhan.com/v1/timingsByCity?city=Milano&country=Italy&method=8"
);
const orarioJson = await data.json();
const orario = orarioJson.data.timings;
let orarioText = document.querySelector(".tempo-preghiera-container");
for (const property in orario) {
if (property == "Sunset"
|| property == "Sunrise"
|| property == "Midnight" ) continue;
let div = document.createElement("div");
div.classList.add("orario");
let text = document.createTextNode(property + " - " + orario[property]);
div.appendChild(text);
orarioText.appendChild(div);
}
};
fetchPreghieraTime();
输出
<div class="container">
div class="tempo-preghiera-container">
<div class="orario">Fajr - 05:30</div>
<div class="orario">Dhuhr - 12:37</div>
<div class="orario">Asr - 15:28</div>
<div class="orario">Maghrib - 17:57</div>
<div class="orario">Isha - 19:27</div>
<div class="orario">Imsak - 05:20</div>
<div class="orario">Midnight - 00:37</div>
</div>
</div>
I will answer the same question, so I will help someone in the future :)
简答
.JSON
格式,
❌你不能将括号与数字变量
一起使用
orario[index]
✅ 括号内需要放一个字符串
(比如["Fajr"]
,相当于写.Fajr
)
所以没有任何方法可以通过 JSON!
访问它
但是... 我找到了适合您的解决方案!
正如你在问题中所说,这种方法在 arrays
中非常有效
所以我们需要做这样的伪代码:
FETCH -> JSON -> ARRAY -> ARRAY[index]
我在网上看到javascript有这个功能,你也可以用!
Object.values(orario);
更多详情:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values
所以...
我把它放在名为 orarioArray 的变量中,所以对你来说很简单!
const orarioArray = Object.values(orario);
现在你只需要将它添加到你的 forEach
循环中
orarioText.forEach((item, index) => {
item.textContent = orarioArray[index];
});
编辑完整代码:
let allTempoContainer = document.querySelector('.all-tempo-container');
let orarioArrayValue;
let orarioArrayName;
const fetchPreghieraTime = async() => {
const data = await fetch('http://api.aladhan.com/v1/timingsByCity?city=Milano&country=Italy&method=8');
const orarioJson = await data.json();
const orario = orarioJson.data.timings;
orarioArrayValue = Object.values(orario);
orarioArrayName = Object.keys(orario);
for (let index = 0; index < orarioArrayName.length; index++) {
createOrarioCard(index);
}
}
function createOrarioCard(index) {
var OrarioCardTemplate = document.querySelectorAll("template")[0];
var OrarioCardClone = OrarioCardTemplate.content.cloneNode(true);
allTempoContainer.appendChild(OrarioCardClone);
let orarioText = document.querySelectorAll('.orario');
let preghieraText = document.querySelectorAll('.nome-preghiera');
preghieraText[index].textContent = orarioArrayName[index];
orarioText[index].textContent = orarioArrayValue[index];
}
fetchPreghieraTime();
<div class="container">
<div class="all-tempo-container">
<!-- here it will generate the code -->
</div>
</div>
<template>
<div class="orario-container" style="display: flex; justify-content: space-between;">
<div class="nome-preghiera">loading...</div>
<div class="orario">loading...</div>
</div>
</template>
<script src="./script.js"></script>
之前的代码:
let orarioText = document.querySelectorAll('.orario');
const fetchPreghieraTime = async() => {
const data = await fetch('http://api.aladhan.com/v1/timingsByCity?city=Milano&country=Italy&method=8');
const orarioJson = await data.json();
const orario = orarioJson.data.timings;
// JSON to Array
const orarioArray = Object.values(orario);
orarioText.forEach((item, index) => {
item.textContent = orarioArray[index];
});
}
fetchPreghieraTime();
<!-- 0 -->
<div class="orario"></div>
<!-- 1 -->
<div class="orario"></div>
<!-- 2 -->
<div class="orario"></div>
<!-- 3 -->
<div class="orario"></div>
<!-- 4 -->
<div class="orario"></div>
我正在努力学习如何使用 fetch()
API 这个周末...
我看到了这个有趣的 API 服务,我试着学习如何使用这个
我遇到了一个小问题,javascript
问题
我想从 .Json
获取数据(这很好用),
但是当我想将值放入 <div>
并且到达 object[index]
时没有显示任何内容
据我所知,这似乎是可能的,
但在这种情况下,不是(...我在互联网上到处搜索,没有结果)
基本上...
这个不工作object[index]; //index variable, is a number
这有效 object.object1; //normal method
我试过的
是的,我尝试了使用 obj1.obj2
的传统方法并且工作正常,得到了我想要的结果!
but is not efficient, like I want.
因为我想通过 index
获取值
并将值放入 <div>
与index
的NodeListOf<element>
完整代码,我写的
open the snippet to see the code
let orarioText = document.querySelectorAll('.orario');
const fetchPreghieraTime = async() => {
const data = await fetch('http://api.aladhan.com/v1/timingsByCity?city=Milano&country=Italy&method=8');
const orarioJson = await data.json();
const orario = orarioJson.data.timings;
orarioText.forEach((item, index) => {
item.textContent = orario[index];
console.log(item.textContent + "" + index);
});
}
fetchPreghieraTime();
<div class="container">
<div class="tempo-preghiera-container">
<!-- 1 -->
<div class="tempo-fajr">
<div class="nome-preghiera">fajr</div>
<div class="orario">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
<!-- 2 -->
<div class="tempo-duhr">
<div class="nome-preghiera">duhr</div>
<div class="orario">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
<!-- 3 -->
<div class="tempo-asr">
<div class="nome-preghiera">asr</div>
<div class="orario">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
<!-- 4 -->
<div class="tempo-maghrib">
<div class="nome-preghiera">maghrib</div>
<div class="orario">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
<!-- 5 -->
<div class="tempo-isha">
<div class="nome-preghiera">isha</div>
<div class="orario">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
</div>
</div>
<script src="./script.js"></script>
高效是什么意思?
- 这是编写更少、更简单代码的想法:
elementClass.forEach((item, index) => {
item.textContent = object[index];
});
- 你可以看到下面的方法是多么低效,那是有效的
elementClass[0].textContent = object.Fajr;
elementClass[1].textContent = object.Dhuhr;
elementClass[2].textContent = object.Asr;
elementClass[3].textContent = object.Maghrib;
elementClass[4].textContent = object.Isha;
如果可以,我想要 更少的代码,或者更简单的解决方案
( 我不希望你给出一个可能更快的程序,不不,对我来说如果是简单的逻辑就足够了 )
(考虑如果有 50 个项目,我是否需要写出对象的所有名称,等等...,这就是原因)
我想到第一个想法是因为 数组...
在数组中,您可以使用带数字的括号,以 0 开头,即(无效)
问题
- 代码无效
let orarioText = document.querySelectorAll('.orario');
//there are 5 elements with the same class
orarioText.forEach((item, index) => {
item.textContent = orarioJson.data.timings[index];
});
- 这很好用
let orarioText = document.querySelectorAll('.orario');
//there are 5 elements with the same class
orarioText.forEach((item, index) => {
item.textContent = orarioJson.data.timings.Fajr; //here you see the [index] is replaced by the actual name
});
如果你也想试试,这是我用的API
here is the API service link, I used
http://api.aladhan.com/v1/timingsByCity?city=Milano&country=Italy&method=8
这是它的样子:
{"code":200,"status":"OK","data":{"timings":{"Fajr":"05:31","Sunrise":"07:19","Dhuhr":"12:37","Asr":"15:26","Sunset":"17:56","Maghrib":"17:56","Isha":"19:26","Imsak":"05:21","Midnight":"00:37"}
如有不明白的问题给您:
你可以写评论,询问更多信息,我会回答:)
我所问内容的简短摘要
我想要这个 HTML
<!-- 0 -->
<div class="myClass"></div>
<!-- 1 -->
<div class="myClass"></div>
<!-- 2 -->
<div class="myClass"></div>
<!-- 3 -->
<div class="myClass"></div>
<!-- 4 -->
<div class="myClass"></div>
在JS
之后变成这样HTML<!-- 0 -->
<div class="myClass">obj1 value</div>
<!-- 1 -->
<div class="myClass">obj2 value</div>
<!-- 2 -->
<div class="myClass">obj3 value</div>
<!-- 3 -->
<div class="myClass">obj4 value</div>
<!-- 4 -->
<div class="myClass">obj5 value</div>
我希望有一个很棒的乐于助人的开发者,
谁有更多的经验,
可以帮助我
(也帮助看到这个问题的未来开发者)
感谢所有社区!
您可以从父元素中获取您需要的 属性 名称。它的 class 名称为“tempo-....”。它只需要更改 HTML,因为您对 dhurh 使用了不同的拼写。因此,请将其与 JSON 响应中的拼写对齐。
以下是如何从“速度”中提取该名称class,然后使用它从响应对象访问时间:
- 查找具有
.parentNode
的父元素
- 用
.className
获取 - 使用
.match
和返回数组中的第一个条目提取“tempo-”之后的部分 - 将第一个字母转换为大写,其余字母转换为小写。
- 作为动态使用属性
class
属性值
let orarioText = document.querySelectorAll('.orario');
const fetchPreghieraTime = async() => {
const data = await fetch('http://api.aladhan.com/v1/timingsByCity?city=Milano&country=Italy&method=8');
const orarioJson = await data.json();
const orario = orarioJson.data.timings;
orarioText.forEach((item, index) => {
let name = item.parentNode.className.match(/(?<=\btempo-)\w+/)[0];
item.textContent = orario[name[0].toUpperCase() + name.slice(1).toLowerCase()];
});
}
fetchPreghieraTime();
<div class="container">
<div class="tempo-preghiera-container">
<!-- 1 -->
<div class="tempo-fajr">
<div class="nome-preghiera">fajr</div>
<div class="orario">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
<!-- 2 -->
<div class="tempo-dhuhr">
<div class="nome-preghiera">duhr</div>
<div class="orario">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
<!-- 3 -->
<div class="tempo-asr">
<div class="nome-preghiera">asr</div>
<div class="orario ">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
<!-- 4 -->
<div class="tempo-maghrib">
<div class="nome-preghiera">maghrib</div>
<div class="orario">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
<!-- 5 -->
<div class="tempo-isha">
<div class="nome-preghiera">isha</div>
<div class="orario">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
</div>
</div>
<script src="./script.js"></script>
试试这个
<div class="container">
<div class="tempo-preghiera-container">
</div>
</div>
const fetchPreghieraTime = async () => {
const data = await fetch(
"http://api.aladhan.com/v1/timingsByCity?city=Milano&country=Italy&method=8"
);
const orarioJson = await data.json();
const orario = orarioJson.data.timings;
let orarioText = document.querySelector(".tempo-preghiera-container");
for (const property in orario) {
if (property == "Sunset"
|| property == "Sunrise"
|| property == "Midnight" ) continue;
let div = document.createElement("div");
div.classList.add("orario");
let text = document.createTextNode(property + " - " + orario[property]);
div.appendChild(text);
orarioText.appendChild(div);
}
};
fetchPreghieraTime();
输出
<div class="container">
div class="tempo-preghiera-container">
<div class="orario">Fajr - 05:30</div>
<div class="orario">Dhuhr - 12:37</div>
<div class="orario">Asr - 15:28</div>
<div class="orario">Maghrib - 17:57</div>
<div class="orario">Isha - 19:27</div>
<div class="orario">Imsak - 05:20</div>
<div class="orario">Midnight - 00:37</div>
</div>
</div>
I will answer the same question, so I will help someone in the future :)
简答
.JSON
格式,
❌你不能将括号与数字变量
一起使用
orario[index]
✅ 括号内需要放一个字符串
(比如["Fajr"]
,相当于写.Fajr
)
所以没有任何方法可以通过 JSON!
访问它但是... 我找到了适合您的解决方案!
正如你在问题中所说,这种方法在 arrays
中非常有效所以我们需要做这样的伪代码:
FETCH -> JSON -> ARRAY -> ARRAY[index]
我在网上看到javascript有这个功能,你也可以用!
Object.values(orario);
更多详情:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values
所以...
我把它放在名为 orarioArray 的变量中,所以对你来说很简单!
const orarioArray = Object.values(orario);
现在你只需要将它添加到你的 forEach
循环中
orarioText.forEach((item, index) => {
item.textContent = orarioArray[index];
});
编辑完整代码:
let allTempoContainer = document.querySelector('.all-tempo-container');
let orarioArrayValue;
let orarioArrayName;
const fetchPreghieraTime = async() => {
const data = await fetch('http://api.aladhan.com/v1/timingsByCity?city=Milano&country=Italy&method=8');
const orarioJson = await data.json();
const orario = orarioJson.data.timings;
orarioArrayValue = Object.values(orario);
orarioArrayName = Object.keys(orario);
for (let index = 0; index < orarioArrayName.length; index++) {
createOrarioCard(index);
}
}
function createOrarioCard(index) {
var OrarioCardTemplate = document.querySelectorAll("template")[0];
var OrarioCardClone = OrarioCardTemplate.content.cloneNode(true);
allTempoContainer.appendChild(OrarioCardClone);
let orarioText = document.querySelectorAll('.orario');
let preghieraText = document.querySelectorAll('.nome-preghiera');
preghieraText[index].textContent = orarioArrayName[index];
orarioText[index].textContent = orarioArrayValue[index];
}
fetchPreghieraTime();
<div class="container">
<div class="all-tempo-container">
<!-- here it will generate the code -->
</div>
</div>
<template>
<div class="orario-container" style="display: flex; justify-content: space-between;">
<div class="nome-preghiera">loading...</div>
<div class="orario">loading...</div>
</div>
</template>
<script src="./script.js"></script>
之前的代码:
let orarioText = document.querySelectorAll('.orario');
const fetchPreghieraTime = async() => {
const data = await fetch('http://api.aladhan.com/v1/timingsByCity?city=Milano&country=Italy&method=8');
const orarioJson = await data.json();
const orario = orarioJson.data.timings;
// JSON to Array
const orarioArray = Object.values(orario);
orarioText.forEach((item, index) => {
item.textContent = orarioArray[index];
});
}
fetchPreghieraTime();
<!-- 0 -->
<div class="orario"></div>
<!-- 1 -->
<div class="orario"></div>
<!-- 2 -->
<div class="orario"></div>
<!-- 3 -->
<div class="orario"></div>
<!-- 4 -->
<div class="orario"></div>