0

I have a json file. I would like to write the content from it into two divs. If json.length % 2 === 0 then write in <div id="data1"> else write it in <div id="data2">.

I recieve the json file, but it only writes the 1st if sentence.

I hope the code will make more sense then I do =)

var data1 = document.getElementById("data1");
var data2 = document.getElementById("data2");
loadJSON(function(json) {
  var l = Object.keys(json).length;
  console.log("json start");
  for (var i = 0; i <= l; i++){
    console.log(i);
    if (l % 2 === 0){
      for (x in json) {
        data1.innerHTML="<img src=" + json[x].picture + "/>";
        data1.innerHTML+=json[x].price_thingy.price + json[x].price_thingy.suf;
        console.log("0 " + l); // this never prints
      }
    } else {
      for (x in json) {
        data2.innerHTML="<img src=" + json[x].picture + "/>";
        data2.innerHTML+=json[x].price_thingy.price + json[x].price_thingy.suf;
        console.log("1 " + l); // this never prints
      }
    } 
  }
});

Edit 1:

So, I've changed l % 2 === 0 to i % 2 === 0 and added innerHTML += and things kind of work now. The problem now, is that I get everything two times. So basically I get the same picture and the price in both divs...

Any idea how I could solve this?

DrDoom
  • 325
  • 1
  • 2
  • 12
  • 2
    The content of `json` is _not_ [JSON](https://www.json.org/json-en.html). It's either an object or an array (in which case you [shouldn't be using `for ... in ...`](https://stackoverflow.com/questions/500504/why-is-using-for-in-for-array-iteration-a-bad-idea)) – Andreas Oct 14 '20 at 13:07
  • `i <= l` will cause the script to throw an error – Andreas Oct 14 '20 at 13:08
  • 1
    Your "if (l % 2 == 0)" statement should actually be "if (i % 2 == 0)" :) L is a constant - length of the key array and will always be the same - therefore it will always be in either column 1 or 2, it will never alternate. i is the index of the element in the array and will change with each element, therefore elements should be placed in data1/data2 based on parity of i. – Mario Mucalo Oct 14 '20 at 13:08
  • Don't use `.innerHTML`. There are better alternatives, e.g. [`.insertAdjacentHTML()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElement) – Andreas Oct 14 '20 at 13:09

2 Answers2

1

In your code you apppear to have made a typo. When iterating over an array, your should use the index variable in this case. Therefore the fix should be:

if (i % 2 === 0){
...
}

Instead of:

if (l % 2 === 0){
...
}

As an answer to your secondary problem: You are looping through your json results twice.

Just reorder your code a little bit. The result would be something like this:

loadJSON(function(json) {
  console.log("json start");
  var i = 0;
  for (x in json){
    console.log(i);
    if (i % 2 === 0){
      data1.innerHTML="<img src=" + json[x].picture + "/>";
      data1.innerHTML+=json[x].price_thingy.price + json[x].price_thingy.suf;
      console.log("0 " + l); // this never prints
    } else {
      data2.innerHTML="<img src=" + json[x].picture + "/>";
      data2.innerHTML+=json[x].price_thingy.price + json[x].price_thingy.suf;
      console.log("1 " + l); // this never prints
    }
    i++;
  }
});
Ashwin
  • 541
  • 1
  • 4
  • 7
1

Hi there are multiple ways to accomplish what you are trying. However I think that there are some typos like the l % 2. L does not increase and is the item length of your json thats why I changed it in my snippet.

Now to simplify the code above and get the output I guess you want:

const data1 = document.getElementById("data1");
const data2 = document.getElementById("data2");

const json = {
  a: { picture: 'linkA', price_thingy: { suf: '€', price: 1.99 } },
  b: { picture: 'linkB', price_thingy: { suf: '$', price: 1.99 } },
  c: { picture: 'linkC', price_thingy: { suf: '£', price: 1.99 } },
  d: { picture: 'linkD', price_thingy: { suf: '¥', price: 1.99 } },
}

const l = Object.keys(json).length;

let i = 0;
for (key in json) {
  const value = json[key];
  
  if (i % 2) {
                       // With this as syntax you don't have to use +
    data1.innerHTML += `<img src="${value.picture}"/>`;
    data1.innerHTML += value.price_thingy.price + value.price_thingy.suf;
  } else {
    data2.innerHTML += `<img src="${value.picture}"/>`;
    data2.innerHTML += value.price_thingy.price + value.price_thingy.suf;
  }

  i += 1;
}
<div id='data1'></div>
<div id='data2'></div>
TessavWalstijn
  • 1,698
  • 1
  • 19
  • 36
  • hey. Tahnks for the reply. The 1st example you posted doesn't really change anything. I get two of the same pictures and prices. – DrDoom Oct 14 '20 at 13:27
  • my bad. Iit was overwriting stuff as I forgto to add a plus in innerHTML +=. But now I get the same picture and price in both divs. – DrDoom Oct 14 '20 at 13:36
  • You use `json[x].picture` and to access `.picture` you need to use `value.picture` if you use the last snippet. (Also just updated the last snippet) If I am correct you should be able to get dufferent pictures with `value.picture` – TessavWalstijn Oct 14 '20 at 14:00
  • the whole json consists of objects., so the [key] won't work as it as an array... don't want to be ungratefull, but could you check this out, I think I made everything more clear... https://stackoverflow.com/questions/64355111/javascript-using-for-key-in-json-i-would-like-to-get-every-other-key-note – DrDoom Oct 14 '20 at 14:09
  • I'll try it out and see if I can make it work. But shouldn't `const value` be a `var` since the value i'm trying to access keeps changing? – DrDoom Oct 14 '20 at 14:12
  • another quick question. I do stuff in javascript. How would I convert ${key} to javascript? – DrDoom Oct 14 '20 at 14:17
  • it kind of works. The value is value: [object Object] – DrDoom Oct 14 '20 at 14:19
  • `value` can be a `const` since the variable will be removed from the stack when the code reloops or exit the loop. A good read is [this question](https://stackoverflow.com/questions/48028320/) about `var` vs `let/const`. If I had declared value above the `for (key in json) {` line I could use `var` but I will pick `let` over it because of the clearer way how a [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) behaved against a [`var`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting) – TessavWalstijn Oct 14 '20 at 14:25
  • Updated the snippet this should work and should be more readable – TessavWalstijn Oct 14 '20 at 14:53