List fron nested object using list.js

26 Views Asked by At

I am trying to make a list from data from a geojson file used in open layer. my data looks like

var json_2 = [ {"properties": { "zona": "Italia", "nome": "A"} }, {"properties": { "zona": "Italia", "nome": "I" } } ]

I am not able to do it, also if I tried in many way. I not sure it is possible. To be clear I don't need to do a nested list. I just want to have something like

  • Italia - A
  • Italia - I

It is possible without parse the data?

tried with dot notation and bracket notation too. No way. I prepared a file to do the test

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title></title>
  <link href="style.css" rel="stylesheet" />
</head>
<body>

  <script src="./list.js"></script>
  
  <div id="lista">

  <ul class="list">
  </ul>

</div>

<script> var json_naz_2 = [
{"properties": { "zona": "Italia", "nome": "A"} },
{"properties": { "zona": "Italia", "nome": "I" } }
]
 </script>
 <script>
console.log(json_naz_2); 
console.log(json_naz_2[0]); 
console.log(json_naz_2[0].properties);
console.log(json_naz_2[0].properties.zona);
console.log(json_naz_2[0]["properties"]);
console.log(json_naz_2[0]["properties"]["zona"]);
</script>
 <script >var options = {
valueNames: [ 'zona', 'nome' ],
item: '<li><h3 class="zona"></h3><p class="nome"></p></li>'
  }; </script>

  <script> var userList = new List('lista', options, json_naz_2); </script>
 
</body>
</html>

changed valueNames and item in many way. no lucky

thanks to who can help

1

There are 1 best solutions below

1
a_deeee On

Is this what you are looking for? Parse the values and populate list.

  const mylist = [];
  for (variable in json_naz_2) {
    mystr =
      json_naz_2[variable].properties.zona +
      " - " +
      json_naz_2[variable].properties.nome;
    mylist[variable] = mystr;
    console.log(mystr);
  }
  console.log(mylist, typeof mylist);

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title></title>
    <link href="style.css" rel="stylesheet" />
  </head>
  <body>
    <script src="./list.js"></script>

    <div id="lista">
      <ul class="list"></ul>
    </div>

    <script>
      var json_naz_2 = [
        { properties: { zona: "Italia", nome: "A" } },
        { properties: { zona: "Italia", nome: "I" } },
      ];
    </script>
    <script>
      const mylist = [];
      for (variable in json_naz_2) {
        mystr =
          json_naz_2[variable].properties.zona +
          " - " +
          json_naz_2[variable].properties.nome;
        mylist[variable] = mystr;
        console.log(mystr);
      }
      console.log(mylist, typeof mylist);
    </script>
    <script>
      var options = {
        valueNames: ["zona", "nome"],
        item: '<li><h3 class="zona"></h3><p class="nome"></p></li>',
      };
    </script>

    <script>
      var userList = new List("lista", options, json_naz_2);
    </script>
  </body>
</html>