1

I have a simple json file which includes mathematical operational information. I want to lis json data into inside ul, so that, object key should be header with header class, and its values should list after the each header.

My script file:

{
  "Operations":{
   " Arithmetic Operations" : ["+", "-", "*", "/"],
   "Comparision Operations" : ["Equals","Greater than","Greater than equal to","Less than","Less than equal to"]
  }
}

fetch('./js/data.json')
  .then(function (response) {
    return response.json();
  })
  .then(function (data) {
    fetchList(data['Operations'])
  });

fetchList = data => {
  Object.entries(data).forEach(([key, values]) => {
    let list;
    values.forEach(item => {
      list = `<li class="list">${ item }</li>`;
    });

    const li =
      `<li class="head">${ key }</li>
        ${ list }
    `;

    console.log(li)
    document.querySelector('#operations .lists').innerHTML += li
  });
}

Result shows only last values of each one

<li class="head"> Arithmetic Operations</li>
<li class="list">/</li>
<li class="head">Comparision Operations</li>
<li class="list">Less than equal to</li>
2
  • 3
    list = just overwrites the value each time. I think you meant to use += rather than =, after first initialising list to an empty string. Commented Nov 7, 2020 at 0:23
  • I would say that comment from Robin is the answer. Commented Nov 7, 2020 at 0:25

1 Answer 1

1

Since there are no dupes, I'll answer it. There are two things here.

  1. Replace: =
  2. Append: +=

What you're doing is replacing. What you need to be doing is appending. Your solution is:

let list = "";
values.forEach(item => {
  list += `<li class="list">${ item }</li>`;
});

An example snippet to show you what's happening will be:

var arr = ["One", "Two", "Three"];

var one = "";
arr.forEach(function (a) {
  one = a;
});
console.log(one);

var two = "";
arr.forEach(function (a) {
  two += a;
});
console.log(two);

I hope you understand the cases above with the variables one and two. You're looking for two but you have implemented one.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.