Home > Back-end >  get a object value from a json API by Index in a forEach loop in JavaScript?
get a object value from a json API by Index in a forEach loop in JavaScript?

Time:02-20

I am trying to learn how to use fetch() APIs this weekend...
and I saw this interesting API service, and I tried to learn how to use this

and I get a little problem, with javascript


the problem

I want to get the data from a .Json (and this works fine),
but when I want to put the values in the <div>
and getting by object[index] is not showing anything

from what I know it seems possible,
but in this case, is not (...I search everywhere on the internet, no result)

basically...
this don't work object[index]; //index variable, is a number
this works object.object1; //normal method


what I tried

yes, I tried the traditional method using obj1.obj2
and is working fine, with the result I want!

but is not efficient, like I want.

because I want to get the values by index
and put the value in the <div>
with the index of the NodeListOf<element>


complete code, I wrote

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 >
  <div >
    <!-- 1 -->
    <div >
      <div >fajr</div>
      <div >error</div>
      <!-- this error text, It will change dinamically with JS -->
    </div>
    <!-- 2 -->
    <div >
      <div >duhr</div>
      <div >error</div>
      <!-- this error text, It will change dinamically with JS -->
    </div>
    <!-- 3 -->
    <div >
      <div >asr</div>
      <div >error</div>
      <!-- this error text, It will change dinamically with JS -->
    </div>
    <!-- 4 -->
    <div >
      <div >maghrib</div>
      <div >error</div>
      <!-- this error text, It will change dinamically with JS -->
    </div>
    <!-- 5 -->
    <div >
      <div >isha</div>
      <div >error</div>
      <!-- this error text, It will change dinamically with JS -->
    </div>
  </div>
</div>

<script src="./script.js"></script>


What do I mean by efficient?

  1. this is the idea to write less, simpler code:
elementClass.forEach((item, index) => {
    item.textContent = object[index];
});
  1. you can see how inefficient method below, that is working
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;

if you can I want the less code, or the simpler solution
( I don't want you to give a faster program possible, no no, for me if is simple logic that is enough for me )
(think if I need to write all the name of the object if there is like 50 items, etc..., that is why)

the first Idea is coming to my mind because of arrays...
and in arrays, you can use brackets with a number, that start with 0, and that is (is not working)


the problem

  1. code doesn't work
let orarioText = document.querySelectorAll('.orario');
//there are 5 elements with the same class

orarioText.forEach((item, index) => {

    item.textContent = orarioJson.data.timings[index]; 
});
  1. this is WORKING fine
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  
});

if you want to try also, here is the API I used

here is the API service link, I used
http://api.aladhan.com/v1/timingsByCity?city=Milano&country=Italy&method=8

and this is how it looks:

{"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"}

image of adhan API


in case, is not clear the problem to you:
you can write a comment, asking for more info, I will answer it :)


short summary of what I asked

I want that this HTML

<!-- 0 -->
<div ></div>
<!-- 1 -->
<div ></div>
<!-- 2 -->
<div ></div>
<!-- 3 -->
<div ></div>
<!-- 4 -->
<div ></div>

to become like this HTML after JS

<!-- 0 -->
<div >obj1 value</div>
<!-- 1 -->
<div >obj2 value</div>
<!-- 2 -->
<div >obj3 value</div>
<!-- 3 -->
<div >obj4 value</div>
<!-- 4 -->
<div >obj5 value</div>

I hope there is someone amazing helpful developer, who have more experience,
that can help me (and help also the future developers who see this question)

and thank you all the community!

CodePudding user response:

You can get the property name that you need from the parent element. It has it in its class name "tempo-....". It just needs one change in the HTML, as you used a different spelling for dhurh. So align that with the spelling in the JSON response.

Here is how you can extract that name from that "tempo" class and then use it to access the timing from the response object:

  • Find the parent element with .parentNode
  • Get the class attribute value with .className
  • Extract the part after "tempo-" using .match and the first entry in the returned array
  • Convert the first letter to a capital and the rest to lowercase.
  • Use it as a dynamic property

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 >
  <div >
    <!-- 1 -->
    <div >
      <div >fajr</div>
      <div >error</div>
      <!-- this error text, It will change dinamically with JS -->
    </div>
    <!-- 2 -->
    <div >
      <div >duhr</div>
      <div >error</div>
      <!-- this error text, It will change dinamically with JS -->
    </div>
    <!-- 3 -->
    <div >
      <div >asr</div>
      <div >error</div>
      <!-- this error text, It will change dinamically with JS -->
    </div>
    <!-- 4 -->
    <div >
      <div >maghrib</div>
      <div >error</div>
      <!-- this error text, It will change dinamically with JS -->
    </div>
    <!-- 5 -->
    <div >
      <div >isha</div>
      <div >error</div>
      <!-- this error text, It will change dinamically with JS -->
    </div>
  </div>
</div>

<script src="./script.js"></script>

CodePudding user response:

try this

 <div >
      <div >
      </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();

output

Fajr - 05:31
Dhuhr - 12:37
Asr - 15:26
Maghrib - 17:56
Isha - 19:26
Imsak - 05:21
  • Related